1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
5 # This file is free software, which comes along with NIT. This software is
6 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
7 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
8 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
9 # is kept unaltered, and a notification of the changes is added.
10 # You are allowed to redistribute it and sell it, alone or is a part of
13 # Abstract collection classes and services.
15 # TODO specify the behavior on iterators when collections are modified.
16 module abstract_collection
20 # The root of the collection hierarchy.
22 # Collections modelize finite groups of objects, called elements.
24 # The specific behavior and representation of collections is determined
25 # by the subclasses of the hierarchy.
27 # The main service of Collection is to provide a stable `iterator`
28 # method usable to retrieve all the elements of the collection.
30 # Additional services are provided.
31 # For an implementation point of view, Collection provide a basic
32 # implementation of these services using the `iterator` method.
33 # Subclasses often provide a more efficient implementation.
35 # Because of the `iterator` method, Collections instances can use
36 # the `for` control structure:
38 # var x: Collection[U]
45 # that is equivalent with
47 # var x: Collection[U]
51 # var u = i.item # u is a U
55 interface Collection[E
]
56 # Get a new iterator on the collection.
57 fun iterator
: Iterator[E
] is abstract
59 # Is there no item in the collection?
61 # assert [1,2,3].is_empty == false
62 # assert [1..1[.is_empty == true
63 fun is_empty
: Bool do return length
== 0
65 # Number of items in the collection.
67 # assert [10,20,30].length == 3
68 # assert [20..30[.length == 10
72 for i
in self do nb
+= 1
76 # Is `item` in the collection ?
77 # Comparisons are done with ==
79 # assert [1,2,3].has(2) == true
80 # assert [1,2,3].has(9) == false
81 # assert [1..5[.has(2) == true
82 # assert [1..5[.has(9) == false
83 fun has
(item
: E
): Bool
85 for i
in self do if i
== item
then return true
89 # Is the collection contain only `item`?
90 # Comparisons are done with ==
91 # Return true if the collection is empty.
93 # assert [1,1,1].has_only(1) == true
94 # assert [1,2,3].has_only(1) == false
95 # assert [1..1].has_only(1) == true
96 # assert [1..3].has_only(1) == false
97 # assert [3..3[.has_only(1) == true # empty collection
99 # ENSURE `is_empty implies result == true`
100 fun has_only
(item
: E
): Bool
102 for i
in self do if i
!= item
then return false
106 # How many occurrences of `item` are in the collection?
107 # Comparisons are done with ==
109 # assert [10,20,10].count(10) == 2
110 fun count
(item
: E
): Int
113 for i
in self do if i
== item
then nb
+= 1
117 # Return the first item of the collection
119 # assert [1,2,3].first == 1
126 # Does the collection contain at least each element of `other`?
128 # assert [1,3,4,2].has_all([1..2]) == true
129 # assert [1,3,4,2].has_all([1..5]) == false
131 # Repeated elements in the collections are not considered.
133 # assert [1,1,1].has_all([1]) == true
134 # assert [1..5].has_all([1,1,1]) == true
136 # Note that the default implementation is general and correct for any lawful Collections.
137 # It is memory-efficient but relies on `has` so may be CPU-inefficient for some kind of collections.
138 fun has_all
(other
: Collection[E
]): Bool
140 for x
in other
do if not has
(x
) then return false
145 # Instances of the Iterator class generates a series of elements, one at a time.
146 # They are mainly used with collections.
147 interface Iterator[E
]
150 fun item
: E
is abstract
152 # Jump to the next item.
156 # Is there a current item ?
157 fun is_ok
: Bool is abstract
159 # Iterate over `self`
160 fun iterator
: Iterator[E
] do return self
162 # Post-iteration hook.
164 # Used to inform `self` that the iteration is over.
165 # Specific iterators can use this to free some resources.
167 # Is automatically invoked at the end of `for` structures.
169 # Do nothing by default.
173 # A collection that contains only one item.
175 # Used to pass arguments by reference.
177 # Also used when one want to give asingle element when a full
178 # collection is expected
182 redef fun first
do return item
184 redef fun is_empty
do return false
186 redef fun length
do return 1
188 redef fun has
(an_item
) do return item
== an_item
190 redef fun has_only
(an_item
) do return item
== an_item
192 redef fun count
(an_item
)
194 if item
== an_item
then
201 redef fun iterator
do return new ContainerIterator[E
](self)
204 var item
: E
is writable
207 # This iterator is quite stupid since it is used for only one item.
208 private class ContainerIterator[E
]
210 redef fun item
do return _container
.item
212 redef fun next
do is_ok
= false
214 redef var is_ok
: Bool = true
216 var container
: Container[E
]
219 # Items can be removed from this collection
220 interface RemovableCollection[E
]
227 # assert a.length == 0
230 fun clear
is abstract
232 # Remove an occucence of `item`
234 # var a = [1,2,3,1,2,3]
236 # assert a == [1,3,1,2,3]
237 fun remove
(item
: E
) is abstract
239 # Remove all occurences of `item`
241 # var a = [1,2,3,1,2,3]
243 # assert a == [1,3,1,3]
244 fun remove_all
(item
: E
) do while has
(item
) do remove
(item
)
247 # Items can be added to these collections.
248 interface SimpleCollection[E
]
249 super RemovableCollection[E
]
251 # Add an item in a collection.
255 # assert a.has(3) == true
256 # assert a.has(10) == false
258 # Ensure col.has(item)
259 fun add
(item
: E
) is abstract
261 # Add each item of `coll`.
264 # assert a.has(4) == true
265 # assert a.has(10) == false
266 fun add_all
(coll
: Collection[E
]) do for i
in coll
do add
(i
)
271 # Set is a collection without duplicates (according to `==`)
273 # var s: Set[String] = new ArraySet[String]
275 # var b = "Hel" + "lo"
278 # assert s.has(b) == true
279 interface Set[E
: Object]
280 super SimpleCollection[E
]
282 redef fun has_only
(item
)
295 redef fun count
(item
)
304 # Synonym of remove since there is only one item
305 redef fun remove_all
(item
) do remove
(item
)
307 # Equality is defined on set and means that each set contains the same elements
310 if not other
isa Set[Object] then return false
311 if other
.length
!= length
then return false
312 return has_all
(other
)
315 # Because of the law between `==` and `hash`, `hash` is redefined to be the sum of the hash of the elements
318 # 23 is a magic number empirically determined to be not so bad.
319 var res
= 23 + length
320 # Note: the order of the elements must not change the hash value.
321 # So, unlike usual hash functions, the accumulator is not combined with itself.
322 for e
in self do res
+= e
.hash
326 # Returns the union of this set with the `other` set
327 fun union
(other
: Set[E
]): Set[E
]
335 # Returns the intersection of this set with the `other` set
336 fun intersection
(other
: Set[E
]): Set[E
]
339 for v
in self do if other
.has
(v
) then nhs
.add
(v
)
343 # Returns a new instance of `Set`.
345 # Depends on the subclass, mainly used for copy services
346 # like `union` or `intersection`.
347 protected fun new_set
: Set[E
] is abstract
350 # MapRead are abstract associative collections: `key` -> `item`.
351 interface MapRead[K
: Object, V
]
352 # Get the item at `key`
354 # var x = new HashMap[String, Int]
356 # assert x["four"] == 4
357 # # assert x["five"] #=> abort
359 # If the key is not in the map, `provide_default_value` is called (that aborts by default)
360 # See `get_or_null` and `get_or_default` for safe variations.
361 fun [](key
: K
): V
is abstract
363 # Get the item at `key` or null if `key` is not in the map.
365 # var x = new HashMap[String, Int]
367 # assert x.get_or_null("four") == 4
368 # assert x.get_or_null("five") == null
370 # Note: use `has_key` and `[]` if you need the distinction between a key associated with null, and no key.
371 fun get_or_null
(key
: K
): nullable V
373 if has_key
(key
) then return self[key
]
377 # Get the item at `key` or return `default` if not in map
379 # var x = new HashMap[String, Int]
381 # assert x.get_or_default("four", 40) == 4
382 # assert x.get_or_default("five", 50) == 50
384 fun get_or_default
(key
: K
, default
: V
): V
386 if has_key
(key
) then return self[key
]
390 # Alias for `keys.has`
391 fun has_key
(key
: K
): Bool do return self.keys
.has
(key
)
393 # Get a new iterator on the map.
394 fun iterator
: MapIterator[K
, V
] is abstract
396 # Return the point of view of self on the values only.
397 # Note that `self` and `values` are views on the same data;
398 # therefore any modification of one is visible on the other.
400 # var x = new HashMap[String, Int]
402 # assert x.values.has(4) == true
403 # assert x.values.has(5) == false
404 fun values
: Collection[V
] is abstract
406 # Return the point of view of self on the keys only.
407 # Note that `self` and `keys` are views on the same data;
408 # therefore any modification of one is visible on the other.
410 # var x = new HashMap[String, Int]
412 # assert x.keys.has("four") == true
413 # assert x.keys.has("five") == false
414 fun keys
: Collection[K
] is abstract
416 # Is there no item in the collection?
418 # var x = new HashMap[String, Int]
419 # assert x.is_empty == true
421 # assert x.is_empty == false
422 fun is_empty
: Bool is abstract
424 # Number of items in the collection.
426 # var x = new HashMap[String, Int]
427 # assert x.length == 0
429 # assert x.length == 1
431 # assert x.length == 2
432 fun length
: Int is abstract
434 # Called by the underling implementation of `[]` to provide a default value when a `key` has no value
435 # By default the behavior is to abort.
437 # Note: the value is returned *as is*, implementations may want to store the value in the map before returning it
439 protected fun provide_default_value
(key
: K
): V
do abort
442 # Maps are associative collections: `key` -> `item`.
444 # The main operator over maps is [].
446 # var map: Map[String, Int] = new ArrayMap[String, Int]
448 # map["one"] = 1 # Associate 'one' to '1'
449 # map["two"] = 2 # Associate 'two' to '2'
450 # assert map["one"] == 1
451 # assert map["two"] == 2
453 # Instances of maps can be used with the for structure
455 # for key, value in map do
456 # assert (key == "one" and value == 1) or (key == "two" and value == 2)
459 # The keys and values in the map can also be manipulated directly with the `keys` and `values` methods.
461 # assert map.keys.has("one") == true
462 # assert map.keys.has("tree") == false
463 # assert map.values.has(1) == true
464 # assert map.values.has(3) == false
466 interface Map[K
: Object, V
]
469 # Set the `value` at `key`.
471 # Values can then get retrieved with `[]`.
473 # var x = new HashMap[String, Int]
475 # assert x["four"] == 4
477 # If the key was associated with a value, this old value is discarded
478 # and replaced with the new one.
481 # assert x["four"] == 40
482 # assert x.values.has(4) == false
484 fun []=(key
: K
, value
: V
) is abstract
486 # Add each (key,value) of `map` into `self`.
487 # If a same key exists in `map` and `self`, then the value in self is discarded.
489 # It is the analogous of `SimpleCollection::add_all`
491 # var x = new HashMap[String, Int]
494 # var y = new HashMap[String, Int]
498 # assert x["four"] == 40
499 # assert x["five"] == 5
500 # assert x["nine"] == 90
501 fun recover_with
(map
: MapRead[K
, V
])
512 # var x = new HashMap[String, Int]
515 # assert x.keys.has("four") == false
518 fun clear
is abstract
520 redef fun values
: RemovableCollection[V
] is abstract
522 redef fun keys
: RemovableCollection[K
] is abstract
526 interface MapIterator[K
: Object, V
]
529 fun item
: V
is abstract
531 # The key of the current item.
533 fun key
: K
is abstract
535 # Jump to the next item.
539 # Is there a current item ?
540 fun is_ok
: Bool is abstract
542 # Set a new `item` at `key`.
543 #fun item=(item: E) is abstract
545 # Post-iteration hook.
547 # Used to inform `self` that the iteration is over.
548 # Specific iterators can use this to free some resources.
550 # Is automatically invoked at the end of `for` structures.
552 # Do nothing by default.
556 # Iterator on a 'keys' point of view of a map
557 class MapKeysIterator[K
: Object, V
]
559 # The original iterator
560 var original_iterator
: MapIterator[K
, V
]
562 redef fun is_ok
do return self.original_iterator
.is_ok
563 redef fun next
do self.original_iterator
.next
564 redef fun item
do return self.original_iterator
.key
567 # Iterator on a 'values' point of view of a map
568 class MapValuesIterator[K
: Object, V
]
570 # The original iterator
571 var original_iterator
: MapIterator[K
, V
]
573 redef fun is_ok
do return self.original_iterator
.is_ok
574 redef fun next
do self.original_iterator
.next
575 redef fun item
do return self.original_iterator
.item
578 # Sequences are indexed collections.
579 # The first item is 0. The last is `length-1`.
581 # The order is the main caracteristic of sequence
582 # and all concrete implementation of sequences are basically interchangeable.
583 interface SequenceRead[E
]
586 # Get the first item.
587 # Is equivalent with `self[0]`.
590 # assert a.first == 1
592 # REQUIRE `not is_empty`
595 assert not_empty
: not is_empty
599 # Return the index-th element of the sequence.
600 # The first element is 0 and the last is `length-1`
601 # If index is invalid, the program aborts
608 # REQUIRE `index >= 0 and index < length`
609 fun [](index
: Int): E
is abstract
612 # Is equivalent with `self[length-1]`.
617 # REQUIRE `not is_empty`
620 assert not_empty
: not is_empty
621 return self[length-1
]
624 # The index of the first occurrence of `item`.
625 # Return -1 if `item` is not found.
626 # Comparison is done with `==`.
628 # var a = [10,20,30,10,20,30]
629 # assert a.index_of(20) == 1
630 # assert a.index_of(40) == -1
631 fun index_of
(item
: E
): Int do return index_of_from
(item
, 0)
633 # The index of the last occurrence of `item`.
634 # Return -1 if `item` is not found.
635 # Comparison is done with `==`.
637 # var a = [10,20,30,10,20,30]
638 # assert a.last_index_of(20) == 4
639 # assert a.last_index_of(40) == -1
640 fun last_index_of
(item
: E
): Int do return last_index_of_from
(item
, length-1
)
642 # The index of the first occurrence of `item`, starting from pos.
643 # Return -1 if `item` is not found.
644 # Comparison is done with `==`.
646 # var a = [10,20,30,10,20,30]
647 # assert a.index_of_from(20, 3) == 4
648 # assert a.index_of_from(20, 4) == 4
649 # assert a.index_of_from(20, 5) == -1
650 fun index_of_from
(item
: E
, pos
: Int): Int
655 if p
>=pos
and i
.item
== item
then return i
.index
662 # The index of the last occurrence of `item` starting from `pos` and decrementing.
663 # Return -1 if `item` is not found.
664 # Comparison is done with `==`.
666 # var a = [10,20,30,10,20,30]
667 # assert a.last_index_of_from(20, 2) == 1
668 # assert a.last_index_of_from(20, 1) == 1
669 # assert a.last_index_of_from(20, 0) == -1
670 fun last_index_of_from
(item
: E
, pos
: Int): Int
677 if i
.item
== item
then res
= p
684 # Two sequences are equals if they have the same items in the same order.
686 # var a = new List[Int]
690 # assert a == [1,2,3]
691 # assert a != [1,3,2]
694 if not o
isa SequenceRead[nullable Object] then return false
696 if o
.length
!= l
then return false
699 if self[i
] != o
[i
] then return false
705 # Because of the law between `==` and `hash`, `hash` is redefined to be the sum of the hash of the elements
708 # The 17 and 2/3 magic numbers were determined empirically.
709 # Note: the standard hash functions djb2, sbdm and fnv1 were also
710 # tested but were comparable (or worse).
711 var res
= 17 + length
714 if e
!= null then res
+= e
.hash
719 redef fun iterator
: IndexedIterator[E
] is abstract
721 # Gets a new Iterator starting at position `pos`
723 # var iter = [10,20,30,40,50].iterator_from(2)
724 # assert iter.to_a == [30, 40, 50]
725 fun iterator_from
(pos
: Int): IndexedIterator[E
]
728 while pos
> 0 and res
.is_ok
do
735 # Gets an iterator starting at the end and going backwards
737 # var reviter = [1,2,3].reverse_iterator
738 # assert reviter.to_a == [3,2,1]
739 fun reverse_iterator
: IndexedIterator[E
] is abstract
741 # Gets an iterator on the chars of self starting from `pos`
743 # var reviter = [10,20,30,40,50].reverse_iterator_from(2)
744 # assert reviter.to_a == [30,20,10]
745 fun reverse_iterator_from
(pos
: Int): IndexedIterator[E
]
747 var res
= reverse_iterator
748 while pos
> 0 and res
.is_ok
do
756 # Sequence are indexed collection.
757 # The first item is 0. The last is `length-1`.
758 interface Sequence[E
]
759 super SequenceRead[E
]
760 super SimpleCollection[E
]
762 # Set the first item.
763 # Is equivalent with `self[0] = item`.
767 # assert a == [10,2,3]
769 do self[0] = item
end
772 # Is equivalent with `self[length-1] = item`.
776 # assert a == [1,2,10]
778 # If the sequence is empty, `last=` is equivalent with `self[0]=` (thus with `first=`)
780 # var b = new Array[Int]
793 # A synonym of `push`
794 redef fun add
(e
) do push
(e
)
796 # Add an item after the last one.
801 # assert a == [1,2,3,10,20]
802 fun push
(e
: E
) is abstract
804 # Add each item of `coll` after the last.
808 # assert a == [1,2,3,7,8,9]
811 fun append
(coll
: Collection[E
]) do add_all
(coll
)
813 # Remove the last item.
820 # REQUIRE `not is_empty`
821 fun pop
: E
is abstract
823 # Add an item before the first one.
828 # assert a == [20,10,1,2,3]
829 fun unshift
(e
: E
) is abstract
831 # Add all items of `coll` before the first one.
835 # assert a == [7,8,9,1,2,3]
837 # Alias of `insert_at(coll, 0)`
838 fun prepend
(coll
: Collection[E
]) do insert_all
(coll
, 0)
840 # Remove the first item.
841 # The second item thus become the first.
844 # assert a.shift == 1
845 # assert a.shift == 2
848 # REQUIRE `not is_empty`
849 fun shift
: E
is abstract
851 # Set the `item` at `index`.
855 # assert a == [10,200,30]
857 # like with `[]`, index should be between `0` and `length-1`
858 # However, if `index==length`, `[]=` works like `push`.
861 # assert a == [10,200,30,400]
863 # REQUIRE `index >= 0 and index <= length`
864 fun []=(index
: Int, item
: E
) is abstract
866 # Insert an element at a given position, following elements are shifted.
868 # var a = [10, 20, 30, 40]
870 # assert a == [10, 20, 100, 30, 40]
872 # REQUIRE `index >= 0 and index <= length`
873 # ENSURE `self[index] == item`
874 fun insert
(item
: E
, index
: Int) is abstract
876 # Insert all elements at a given position, following elements are shifted.
878 # var a = [10, 20, 30, 40]
879 # a.insert_all([100..102], 2)
880 # assert a == [10, 20, 100, 101, 102, 30, 40]
882 # REQUIRE `index >= 0 and index <= length`
883 # ENSURE `self[index] == coll.first`
884 fun insert_all
(coll
: Collection[E
], index
: Int)
886 assert index
>= 0 and index
< length
887 if index
== length
then
896 # Remove the item at `index` and shift all following elements
900 # assert a == [10,30]
902 # REQUIRE `index >= 0 and index < length`
903 fun remove_at
(index
: Int) is abstract
906 # Iterators on indexed collections.
907 interface IndexedIterator[E
]
909 # The index of the current item.
910 fun index
: Int is abstract
913 # Associative arrays that internally uses couples to represent each (key, value) pairs.
914 # This is an helper class that some specific implementation of Map may implements.
915 interface CoupleMap[K
: Object, V
]
918 # Return the couple of the corresponding key
919 # Return null if the key is no associated element
920 protected fun couple_at
(key
: K
): nullable Couple[K
, V
] is abstract
922 # Return a new iteralot on all couples
923 # Used to provide `iterator` and others
924 protected fun couple_iterator
: Iterator[Couple[K
,V
]] is abstract
926 redef fun iterator
do return new CoupleMapIterator[K
,V
](couple_iterator
)
930 var c
= couple_at
(key
)
932 return provide_default_value
(key
)
939 # Iterator on CoupleMap
941 # Actually it is a wrapper around an iterator of the internal array of the map.
942 private class CoupleMapIterator[K
: Object, V
]
943 super MapIterator[K
, V
]
944 redef fun item
do return _iter
.item
.second
946 #redef fun item=(e) do _iter.item.second = e
948 redef fun key
do return _iter
.item
.first
950 redef fun is_ok
do return _iter
.is_ok
957 var iter
: Iterator[Couple[K
,V
]]
960 # Some tools ###################################################################
962 # Two objects in a simple structure.
965 # The first element of the couple.
966 var first
: F
is writable
968 # The second element of the couple.
969 var second
: S
is writable