fa162955bbb45a450619fb03260ef670ad295ad9
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
144 # Does the collection contain exactly all the elements of `other`?
146 # The same elements must be present in both `self` and `other`,
147 # but the order of the elements in the collections are not considered.
149 # assert [1..3].has_exactly([3,1,2]) == true # the same elements
150 # assert [1..3].has_exactly([3,1]) == false # 2 is not in the array
151 # assert [1..2].has_exactly([3,1,2]) == false # 3 is not in the range
153 # Repeated elements must be present in both collections in the same amount.
154 # So basically it is a multi-set comparison.
156 # assert [1,2,3,2].has_exactly([1,2,2,3]) == true # the same elements
157 # assert [1,2,3,2].has_exactly([1,2,3]) == false # more 2 in the first array
158 # assert [1,2,3].has_exactly([1,2,2,3]) == false # more 2 in the second array
160 # Note that the default implementation is general and correct for any lawful Collections.
161 # It is memory-efficient but relies on `count` so may be CPU-inefficient for some kind of collections.
162 fun has_exactly
(other
: Collection[E
]): Bool
164 if length
!= other
.length
then return false
165 for e
in self do if self.count
(e
) != other
.count
(e
) then return false
170 # Instances of the Iterator class generates a series of elements, one at a time.
171 # They are mainly used with collections.
172 interface Iterator[E
]
175 fun item
: E
is abstract
177 # Jump to the next item.
181 # Is there a current item ?
182 fun is_ok
: Bool is abstract
184 # Iterate over `self`
185 fun iterator
: Iterator[E
] do return self
187 # Post-iteration hook.
189 # Used to inform `self` that the iteration is over.
190 # Specific iterators can use this to free some resources.
192 # Is automatically invoked at the end of `for` structures.
194 # Do nothing by default.
198 # A collection that contains only one item.
200 # Used to pass arguments by reference.
202 # Also used when one want to give asingle element when a full
203 # collection is expected
207 redef fun first
do return item
209 redef fun is_empty
do return false
211 redef fun length
do return 1
213 redef fun has
(an_item
) do return item
== an_item
215 redef fun has_only
(an_item
) do return item
== an_item
217 redef fun count
(an_item
)
219 if item
== an_item
then
226 redef fun iterator
do return new ContainerIterator[E
](self)
229 var item
: E
is writable
232 # This iterator is quite stupid since it is used for only one item.
233 private class ContainerIterator[E
]
235 redef fun item
do return _container
.item
237 redef fun next
do is_ok
= false
239 redef var is_ok
: Bool = true
241 var container
: Container[E
]
244 # Items can be removed from this collection
245 interface RemovableCollection[E
]
252 # assert a.length == 0
255 fun clear
is abstract
257 # Remove an occucence of `item`
259 # var a = [1,2,3,1,2,3]
261 # assert a == [1,3,1,2,3]
262 fun remove
(item
: E
) is abstract
264 # Remove all occurences of `item`
266 # var a = [1,2,3,1,2,3]
268 # assert a == [1,3,1,3]
269 fun remove_all
(item
: E
) do while has
(item
) do remove
(item
)
272 # Items can be added to these collections.
273 interface SimpleCollection[E
]
274 super RemovableCollection[E
]
276 # Add an item in a collection.
280 # assert a.has(3) == true
281 # assert a.has(10) == false
283 # Ensure col.has(item)
284 fun add
(item
: E
) is abstract
286 # Add each item of `coll`.
289 # assert a.has(4) == true
290 # assert a.has(10) == false
291 fun add_all
(coll
: Collection[E
]) do for i
in coll
do add
(i
)
296 # Set is a collection without duplicates (according to `==`)
298 # var s: Set[String] = new ArraySet[String]
300 # var b = "Hel" + "lo"
303 # assert s.has(b) == true
304 interface Set[E
: Object]
305 super SimpleCollection[E
]
307 redef fun has_only
(item
)
320 redef fun count
(item
)
329 # Synonym of remove since there is only one item
330 redef fun remove_all
(item
) do remove
(item
)
332 # Equality is defined on set and means that each set contains the same elements
335 if not other
isa Set[Object] then return false
336 if other
.length
!= length
then return false
337 return has_all
(other
)
340 # Because of the law between `==` and `hash`, `hash` is redefined to be the sum of the hash of the elements
343 # 23 is a magic number empirically determined to be not so bad.
344 var res
= 23 + length
345 # Note: the order of the elements must not change the hash value.
346 # So, unlike usual hash functions, the accumulator is not combined with itself.
347 for e
in self do res
+= e
.hash
351 # Returns the union of this set with the `other` set
352 fun union
(other
: Set[E
]): Set[E
]
360 # Returns the intersection of this set with the `other` set
361 fun intersection
(other
: Set[E
]): Set[E
]
364 for v
in self do if other
.has
(v
) then nhs
.add
(v
)
368 # Returns a new instance of `Set`.
370 # Depends on the subclass, mainly used for copy services
371 # like `union` or `intersection`.
372 protected fun new_set
: Set[E
] is abstract
375 # MapRead are abstract associative collections: `key` -> `item`.
376 interface MapRead[K
: Object, V
]
377 # Get the item at `key`
379 # var x = new HashMap[String, Int]
381 # assert x["four"] == 4
382 # # assert x["five"] #=> abort
384 # If the key is not in the map, `provide_default_value` is called (that aborts by default)
385 # See `get_or_null` and `get_or_default` for safe variations.
386 fun [](key
: K
): V
is abstract
388 # Get the item at `key` or null if `key` is not in the map.
390 # var x = new HashMap[String, Int]
392 # assert x.get_or_null("four") == 4
393 # assert x.get_or_null("five") == null
395 # Note: use `has_key` and `[]` if you need the distinction between a key associated with null, and no key.
396 fun get_or_null
(key
: K
): nullable V
398 if has_key
(key
) then return self[key
]
402 # Get the item at `key` or return `default` if not in map
404 # var x = new HashMap[String, Int]
406 # assert x.get_or_default("four", 40) == 4
407 # assert x.get_or_default("five", 50) == 50
409 fun get_or_default
(key
: K
, default
: V
): V
411 if has_key
(key
) then return self[key
]
415 # Alias for `keys.has`
416 fun has_key
(key
: K
): Bool do return self.keys
.has
(key
)
418 # Get a new iterator on the map.
419 fun iterator
: MapIterator[K
, V
] is abstract
421 # Return the point of view of self on the values only.
422 # Note that `self` and `values` are views on the same data;
423 # therefore any modification of one is visible on the other.
425 # var x = new HashMap[String, Int]
427 # assert x.values.has(4) == true
428 # assert x.values.has(5) == false
429 fun values
: Collection[V
] is abstract
431 # Return the point of view of self on the keys only.
432 # Note that `self` and `keys` are views on the same data;
433 # therefore any modification of one is visible on the other.
435 # var x = new HashMap[String, Int]
437 # assert x.keys.has("four") == true
438 # assert x.keys.has("five") == false
439 fun keys
: Collection[K
] is abstract
441 # Is there no item in the collection?
443 # var x = new HashMap[String, Int]
444 # assert x.is_empty == true
446 # assert x.is_empty == false
447 fun is_empty
: Bool is abstract
449 # Number of items in the collection.
451 # var x = new HashMap[String, Int]
452 # assert x.length == 0
454 # assert x.length == 1
456 # assert x.length == 2
457 fun length
: Int is abstract
459 # Called by the underling implementation of `[]` to provide a default value when a `key` has no value
460 # By default the behavior is to abort.
462 # Note: the value is returned *as is*, implementations may want to store the value in the map before returning it
464 protected fun provide_default_value
(key
: K
): V
do abort
467 # Maps are associative collections: `key` -> `item`.
469 # The main operator over maps is [].
471 # var map: Map[String, Int] = new ArrayMap[String, Int]
473 # map["one"] = 1 # Associate 'one' to '1'
474 # map["two"] = 2 # Associate 'two' to '2'
475 # assert map["one"] == 1
476 # assert map["two"] == 2
478 # Instances of maps can be used with the for structure
480 # for key, value in map do
481 # assert (key == "one" and value == 1) or (key == "two" and value == 2)
484 # The keys and values in the map can also be manipulated directly with the `keys` and `values` methods.
486 # assert map.keys.has("one") == true
487 # assert map.keys.has("tree") == false
488 # assert map.values.has(1) == true
489 # assert map.values.has(3) == false
491 interface Map[K
: Object, V
]
494 # Set the `value` at `key`.
496 # Values can then get retrieved with `[]`.
498 # var x = new HashMap[String, Int]
500 # assert x["four"] == 4
502 # If the key was associated with a value, this old value is discarded
503 # and replaced with the new one.
506 # assert x["four"] == 40
507 # assert x.values.has(4) == false
509 fun []=(key
: K
, value
: V
) is abstract
511 # Add each (key,value) of `map` into `self`.
512 # If a same key exists in `map` and `self`, then the value in self is discarded.
514 # It is the analogous of `SimpleCollection::add_all`
516 # var x = new HashMap[String, Int]
519 # var y = new HashMap[String, Int]
523 # assert x["four"] == 40
524 # assert x["five"] == 5
525 # assert x["nine"] == 90
526 fun recover_with
(map
: MapRead[K
, V
])
537 # var x = new HashMap[String, Int]
540 # assert x.keys.has("four") == false
543 fun clear
is abstract
545 redef fun values
: RemovableCollection[V
] is abstract
547 redef fun keys
: RemovableCollection[K
] is abstract
551 interface MapIterator[K
: Object, V
]
554 fun item
: V
is abstract
556 # The key of the current item.
558 fun key
: K
is abstract
560 # Jump to the next item.
564 # Is there a current item ?
565 fun is_ok
: Bool is abstract
567 # Set a new `item` at `key`.
568 #fun item=(item: E) is abstract
570 # Post-iteration hook.
572 # Used to inform `self` that the iteration is over.
573 # Specific iterators can use this to free some resources.
575 # Is automatically invoked at the end of `for` structures.
577 # Do nothing by default.
581 # Iterator on a 'keys' point of view of a map
582 class MapKeysIterator[K
: Object, V
]
584 # The original iterator
585 var original_iterator
: MapIterator[K
, V
]
587 redef fun is_ok
do return self.original_iterator
.is_ok
588 redef fun next
do self.original_iterator
.next
589 redef fun item
do return self.original_iterator
.key
592 # Iterator on a 'values' point of view of a map
593 class MapValuesIterator[K
: Object, V
]
595 # The original iterator
596 var original_iterator
: MapIterator[K
, V
]
598 redef fun is_ok
do return self.original_iterator
.is_ok
599 redef fun next
do self.original_iterator
.next
600 redef fun item
do return self.original_iterator
.item
603 # Sequences are indexed collections.
604 # The first item is 0. The last is `length-1`.
606 # The order is the main caracteristic of sequence
607 # and all concrete implementation of sequences are basically interchangeable.
608 interface SequenceRead[E
]
611 # Get the first item.
612 # Is equivalent with `self[0]`.
615 # assert a.first == 1
617 # REQUIRE `not is_empty`
620 assert not_empty
: not is_empty
624 # Return the index-th element of the sequence.
625 # The first element is 0 and the last is `length-1`
626 # If index is invalid, the program aborts
633 # REQUIRE `index >= 0 and index < length`
634 fun [](index
: Int): E
is abstract
637 # Is equivalent with `self[length-1]`.
642 # REQUIRE `not is_empty`
645 assert not_empty
: not is_empty
646 return self[length-1
]
649 # The index of the first occurrence of `item`.
650 # Return -1 if `item` is not found.
651 # Comparison is done with `==`.
653 # var a = [10,20,30,10,20,30]
654 # assert a.index_of(20) == 1
655 # assert a.index_of(40) == -1
656 fun index_of
(item
: E
): Int do return index_of_from
(item
, 0)
658 # The index of the last occurrence of `item`.
659 # Return -1 if `item` is not found.
660 # Comparison is done with `==`.
662 # var a = [10,20,30,10,20,30]
663 # assert a.last_index_of(20) == 4
664 # assert a.last_index_of(40) == -1
665 fun last_index_of
(item
: E
): Int do return last_index_of_from
(item
, length-1
)
667 # The index of the first occurrence of `item`, starting from pos.
668 # Return -1 if `item` is not found.
669 # Comparison is done with `==`.
671 # var a = [10,20,30,10,20,30]
672 # assert a.index_of_from(20, 3) == 4
673 # assert a.index_of_from(20, 4) == 4
674 # assert a.index_of_from(20, 5) == -1
675 fun index_of_from
(item
: E
, pos
: Int): Int
680 if p
>=pos
and i
.item
== item
then return i
.index
687 # The index of the last occurrence of `item` starting from `pos` and decrementing.
688 # Return -1 if `item` is not found.
689 # Comparison is done with `==`.
691 # var a = [10,20,30,10,20,30]
692 # assert a.last_index_of_from(20, 2) == 1
693 # assert a.last_index_of_from(20, 1) == 1
694 # assert a.last_index_of_from(20, 0) == -1
695 fun last_index_of_from
(item
: E
, pos
: Int): Int
702 if i
.item
== item
then res
= p
709 # Two sequences are equals if they have the same items in the same order.
711 # var a = new List[Int]
715 # assert a == [1,2,3]
716 # assert a != [1,3,2]
719 if not o
isa SequenceRead[nullable Object] then return false
721 if o
.length
!= l
then return false
724 if self[i
] != o
[i
] then return false
730 # Because of the law between `==` and `hash`, `hash` is redefined to be the sum of the hash of the elements
733 # The 17 and 2/3 magic numbers were determined empirically.
734 # Note: the standard hash functions djb2, sbdm and fnv1 were also
735 # tested but were comparable (or worse).
736 var res
= 17 + length
739 if e
!= null then res
+= e
.hash
744 redef fun iterator
: IndexedIterator[E
] is abstract
746 # Gets a new Iterator starting at position `pos`
748 # var iter = [10,20,30,40,50].iterator_from(2)
749 # assert iter.to_a == [30, 40, 50]
750 fun iterator_from
(pos
: Int): IndexedIterator[E
]
753 while pos
> 0 and res
.is_ok
do
760 # Gets an iterator starting at the end and going backwards
762 # var reviter = [1,2,3].reverse_iterator
763 # assert reviter.to_a == [3,2,1]
764 fun reverse_iterator
: IndexedIterator[E
] is abstract
766 # Gets an iterator on the chars of self starting from `pos`
768 # var reviter = [10,20,30,40,50].reverse_iterator_from(2)
769 # assert reviter.to_a == [30,20,10]
770 fun reverse_iterator_from
(pos
: Int): IndexedIterator[E
]
772 var res
= reverse_iterator
773 while pos
> 0 and res
.is_ok
do
781 # Sequence are indexed collection.
782 # The first item is 0. The last is `length-1`.
783 interface Sequence[E
]
784 super SequenceRead[E
]
785 super SimpleCollection[E
]
787 # Set the first item.
788 # Is equivalent with `self[0] = item`.
792 # assert a == [10,2,3]
794 do self[0] = item
end
797 # Is equivalent with `self[length-1] = item`.
801 # assert a == [1,2,10]
803 # If the sequence is empty, `last=` is equivalent with `self[0]=` (thus with `first=`)
805 # var b = new Array[Int]
818 # A synonym of `push`
819 redef fun add
(e
) do push
(e
)
821 # Add an item after the last one.
826 # assert a == [1,2,3,10,20]
827 fun push
(e
: E
) is abstract
829 # Add each item of `coll` after the last.
833 # assert a == [1,2,3,7,8,9]
836 fun append
(coll
: Collection[E
]) do add_all
(coll
)
838 # Remove the last item.
845 # REQUIRE `not is_empty`
846 fun pop
: E
is abstract
848 # Add an item before the first one.
853 # assert a == [20,10,1,2,3]
854 fun unshift
(e
: E
) is abstract
856 # Add all items of `coll` before the first one.
860 # assert a == [7,8,9,1,2,3]
862 # Alias of `insert_at(coll, 0)`
863 fun prepend
(coll
: Collection[E
]) do insert_all
(coll
, 0)
865 # Remove the first item.
866 # The second item thus become the first.
869 # assert a.shift == 1
870 # assert a.shift == 2
873 # REQUIRE `not is_empty`
874 fun shift
: E
is abstract
876 # Set the `item` at `index`.
880 # assert a == [10,200,30]
882 # like with `[]`, index should be between `0` and `length-1`
883 # However, if `index==length`, `[]=` works like `push`.
886 # assert a == [10,200,30,400]
888 # REQUIRE `index >= 0 and index <= length`
889 fun []=(index
: Int, item
: E
) is abstract
891 # Insert an element at a given position, following elements are shifted.
893 # var a = [10, 20, 30, 40]
895 # assert a == [10, 20, 100, 30, 40]
897 # REQUIRE `index >= 0 and index <= length`
898 # ENSURE `self[index] == item`
899 fun insert
(item
: E
, index
: Int) is abstract
901 # Insert all elements at a given position, following elements are shifted.
903 # var a = [10, 20, 30, 40]
904 # a.insert_all([100..102], 2)
905 # assert a == [10, 20, 100, 101, 102, 30, 40]
907 # REQUIRE `index >= 0 and index <= length`
908 # ENSURE `self[index] == coll.first`
909 fun insert_all
(coll
: Collection[E
], index
: Int)
911 assert index
>= 0 and index
< length
912 if index
== length
then
921 # Remove the item at `index` and shift all following elements
925 # assert a == [10,30]
927 # REQUIRE `index >= 0 and index < length`
928 fun remove_at
(index
: Int) is abstract
931 # Iterators on indexed collections.
932 interface IndexedIterator[E
]
934 # The index of the current item.
935 fun index
: Int is abstract
938 # Associative arrays that internally uses couples to represent each (key, value) pairs.
939 # This is an helper class that some specific implementation of Map may implements.
940 interface CoupleMap[K
: Object, V
]
943 # Return the couple of the corresponding key
944 # Return null if the key is no associated element
945 protected fun couple_at
(key
: K
): nullable Couple[K
, V
] is abstract
947 # Return a new iteralot on all couples
948 # Used to provide `iterator` and others
949 protected fun couple_iterator
: Iterator[Couple[K
,V
]] is abstract
951 redef fun iterator
do return new CoupleMapIterator[K
,V
](couple_iterator
)
955 var c
= couple_at
(key
)
957 return provide_default_value
(key
)
964 # Iterator on CoupleMap
966 # Actually it is a wrapper around an iterator of the internal array of the map.
967 private class CoupleMapIterator[K
: Object, V
]
968 super MapIterator[K
, V
]
969 redef fun item
do return _iter
.item
.second
971 #redef fun item=(e) do _iter.item.second = e
973 redef fun key
do return _iter
.item
.first
975 redef fun is_ok
do return _iter
.is_ok
982 var iter
: Iterator[Couple[K
,V
]]
985 # Some tools ###################################################################
987 # Two objects in a simple structure.
990 # The first element of the couple.
991 var first
: F
is writable
993 # The second element of the couple.
994 var second
: S
is writable