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 # Is the collection contains all the elements of `other`?
128 # assert [1,1,1].has_all([1]) == true
129 # assert [1,1,1].has_all([1,2]) == false
130 # assert [1,3,4,2].has_all([1..2]) == true
131 # assert [1,3,4,2].has_all([1..5]) == false
132 fun has_all
(other
: Collection[E
]): Bool
134 for x
in other
do if not has
(x
) then return false
139 # Instances of the Iterator class generates a series of elements, one at a time.
140 # They are mainly used with collections.
141 interface Iterator[E
]
144 fun item
: E
is abstract
146 # Jump to the next item.
150 # Is there a current item ?
151 fun is_ok
: Bool is abstract
153 # Iterate over `self`
154 fun iterator
: Iterator[E
] do return self
157 # A collection that contains only one item.
159 # Used to pass arguments by reference.
161 # Also used when one want to give asingle element when a full
162 # collection is expected
166 redef fun first
do return item
168 redef fun is_empty
do return false
170 redef fun length
do return 1
172 redef fun has
(an_item
) do return item
== an_item
174 redef fun has_only
(an_item
) do return item
== an_item
176 redef fun count
(an_item
)
178 if item
== an_item
then
185 redef fun iterator
do return new ContainerIterator[E
](self)
187 # Create a new instance with a given initial value.
188 init(e
: E
) do item
= e
194 # This iterator is quite stupid since it is used for only one item.
195 private class ContainerIterator[E
]
197 redef fun item
do return _container
.item
199 redef fun next
do is_ok
= false
201 init(c
: Container[E
]) do _container
= c
203 redef var is_ok
: Bool = true
205 var _container
: Container[E
]
208 # Items can be removed from this collection
209 interface RemovableCollection[E
]
216 # assert a.length == 0
219 fun clear
is abstract
221 # Remove an occucence of `item`
223 # var a = [1,2,3,1,2,3]
225 # assert a == [1,3,1,2,3]
226 fun remove
(item
: E
) is abstract
228 # Remove all occurences of `item`
230 # var a = [1,2,3,1,2,3]
232 # assert a == [1,3,1,3]
233 fun remove_all
(item
: E
) do while has
(item
) do remove
(item
)
236 # Items can be added to these collections.
237 interface SimpleCollection[E
]
238 super RemovableCollection[E
]
240 # Add an item in a collection.
244 # assert a.has(3) == true
245 # assert a.has(10) == false
247 # Ensure col.has(item)
248 fun add
(item
: E
) is abstract
250 # Add each item of `coll`.
253 # assert a.has(4) == true
254 # assert a.has(10) == false
255 fun add_all
(coll
: Collection[E
]) do for i
in coll
do add
(i
)
260 # Set is a collection without duplicates (according to `==`)
262 # var s: Set[String] = new ArraySet[String]
264 # var b = "Hel" + "lo"
267 # assert s.has(b) == true
268 interface Set[E
: Object]
269 super SimpleCollection[E
]
271 redef fun has_only
(item
)
284 redef fun count
(item
)
293 # Synonym of remove since there is only one item
294 redef fun remove_all
(item
) do remove
(item
)
296 # Equality is defined on set and means that each set contains the same elements
299 if not other
isa Set[Object] then return false
300 if other
.length
!= length
then return false
301 return has_all
(other
)
304 # Because of the law between `==` and `hash`, `hash` is redefined to be the sum of the hash of the elements
308 for e
in self do res
+= res
.hash
312 # Returns the union of this set with the `other` set
313 fun union
(other
: Set[E
]): Set[E
]
321 # Returns the intersection of this set with the `other` set
322 fun intersection
(other
: Set[E
]): Set[E
]
325 for v
in self do if other
.has
(v
) then nhs
.add
(v
)
329 protected fun new_set
: Set[E
] is abstract
332 # MapRead are abstract associative collections: `key` -> `item`.
333 interface MapRead[K
: Object, E
]
334 # Get the item at `key`
336 # var x = new HashMap[String, Int]
338 # assert x["four"] == 4
339 # # assert x["five"] #=> abort
341 # If the key is not in the map, `provide_default_value` is called (that aborts by default)
342 # See `get_or_null` and `get_or_default` for safe variations.
343 fun [](key
: K
): E
is abstract
345 # Get the item at `key` or null if `key` is not in the map.
347 # var x = new HashMap[String, Int]
349 # assert x.get_or_null("four") == 4
350 # assert x.get_or_null("five") == null
352 # Note: use `has_key` and `[]` if you need the distinction bewteen a key associated with null, and no key.
353 fun get_or_null
(key
: K
): nullable E
355 if has_key
(key
) then return self[key
]
359 # Get the item at `key` or return `default` if not in map
361 # var x = new HashMap[String, Int]
363 # assert x.get_or_default("four", 40) == 4
364 # assert x.get_or_default("five", 50) == 50
366 fun get_or_default
(key
: K
, default
: E
): E
368 if has_key
(key
) then return self[key
]
372 # Depreciated alias for `keys.has`
373 fun has_key
(key
: K
): Bool do return self.keys
.has
(key
)
375 # Get a new iterator on the map.
376 fun iterator
: MapIterator[K
, E
] is abstract
378 # Return the point of view of self on the values only.
379 # Note that `self` and `values` are views on the same data;
380 # therefore any modification of one is visible on the other.
382 # var x = new HashMap[String, Int]
384 # assert x.values.has(4) == true
385 # assert x.values.has(5) == false
386 fun values
: Collection[E
] is abstract
388 # Return the point of view of self on the keys only.
389 # Note that `self` and `keys` are views on the same data;
390 # therefore any modification of one is visible on the other.
392 # var x = new HashMap[String, Int]
394 # assert x.keys.has("four") == true
395 # assert x.keys.has("five") == false
396 fun keys
: Collection[K
] is abstract
398 # Is there no item in the collection?
400 # var x = new HashMap[String, Int]
401 # assert x.is_empty == true
403 # assert x.is_empty == false
404 fun is_empty
: Bool is abstract
406 # Number of items in the collection.
408 # var x = new HashMap[String, Int]
409 # assert x.length == 0
411 # assert x.length == 1
413 # assert x.length == 2
414 fun length
: Int is abstract
416 # Called by the underling implementation of `[]` to provide a default value when a `key` has no value
417 # By default the behavior is to abort.
419 # Note: the value is returned *as is*, implementations may want to store the value in the map before returning it
421 protected fun provide_default_value
(key
: K
): E
do abort
424 # Maps are associative collections: `key` -> `item`.
426 # The main operator over maps is [].
428 # var map: Map[String, Int] = new ArrayMap[String, Int]
430 # map["one"] = 1 # Associate 'one' to '1'
431 # map["two"] = 2 # Associate 'two' to '2'
432 # assert map["one"] == 1
433 # assert map["two"] == 2
435 # Instances of maps can be used with the for structure
437 # for key, value in map do
438 # assert (key == "one" and value == 1) or (key == "two" and value == 2)
441 # The keys and values in the map can also be manipulated directly with the `keys` and `values` methods.
443 # assert map.keys.has("one") == true
444 # assert map.keys.has("tree") == false
445 # assert map.values.has(1) == true
446 # assert map.values.has(3) == false
448 interface Map[K
: Object, E
]
451 # Set the `value` at `key`.
453 # Values can then get retrieved with `[]`.
455 # var x = new HashMap[String, Int]
457 # assert x["four"] == 4
459 # If the key was associated with a value, this old value is discarted
460 # and replaced with the new one.
463 # assert x["four"] == 40
464 # assert x.values.has(4) == false
466 fun []=(key
: K
, value
: E
) is abstract
468 # Add each (key,value) of `map` into `self`.
469 # If a same key exists in `map` and `self`, then the value in self is discarded.
471 # It is the analogous of `SimpleCollection::add_all`
473 # var x = new HashMap[String, Int]
476 # var y = new HashMap[String, Int]
480 # assert x["four"] == 40
481 # assert x["five"] == 5
482 # assert x["nine"] == 90
483 fun recover_with
(map
: Map[K
, E
])
494 # var x = new HashMap[String, Int]
497 # assert x.keys.has("four") == false
500 fun clear
is abstract
502 redef fun values
: RemovableCollection[E
] is abstract
504 redef fun keys
: RemovableCollection[K
] is abstract
508 interface MapIterator[K
: Object, E
]
511 fun item
: E
is abstract
513 # The key of the current item.
515 fun key
: K
is abstract
517 # Jump to the next item.
521 # Is there a current item ?
522 fun is_ok
: Bool is abstract
524 # Set a new `item` at `key`.
525 #fun item=(item: E) is abstract
528 # Iterator on a 'keys' point of view of a map
529 class MapKeysIterator[K
: Object, V
]
531 # The original iterator
532 var original_iterator
: MapIterator[K
, V
]
534 redef fun is_ok
do return self.original_iterator
.is_ok
535 redef fun next
do self.original_iterator
.next
536 redef fun item
do return self.original_iterator
.key
539 # Iterator on a 'values' point of view of a map
540 class MapValuesIterator[K
: Object, V
]
542 # The original iterator
543 var original_iterator
: MapIterator[K
, V
]
545 redef fun is_ok
do return self.original_iterator
.is_ok
546 redef fun next
do self.original_iterator
.next
547 redef fun item
do return self.original_iterator
.item
550 # Sequences are indexed collections.
551 # The first item is 0. The last is `length-1`.
553 # The order is the main caracteristic of sequence
554 # and all concrete implementation of sequences are basically interchangeable.
555 interface SequenceRead[E
]
558 # Get the first item.
559 # Is equivalent with `self[0]`.
562 # assert a.first == 1
564 # REQUIRE `not is_empty`
567 assert not_empty
: not is_empty
571 # Return the index-th element of the sequence.
572 # The first element is 0 and the last is `length-1`
573 # If index is invalid, the program aborts
580 # REQUIRE `index >= 0 and index < length`
581 fun [](index
: Int): E
is abstract
584 # Is equivalent with `self[length-1]`.
589 # REQUIRE `not is_empty`
592 assert not_empty
: not is_empty
593 return self[length-1
]
596 # The index of the first occurrence of `item`.
597 # Return -1 if `item` is not found.
598 # Comparison is done with `==`.
600 # var a = [10,20,30,10,20,30]
601 # assert a.index_of(20) == 1
602 # assert a.index_of(40) == -1
603 fun index_of
(item
: E
): Int do return index_of_from
(item
, 0)
605 # The index of the last occurrence of `item`.
606 # Return -1 if `item` is not found.
607 # Comparison is done with `==`.
609 # var a = [10,20,30,10,20,30]
610 # assert a.last_index_of(20) == 4
611 # assert a.last_index_of(40) == -1
612 fun last_index_of
(item
: E
): Int do return last_index_of_from
(item
, length-1
)
614 # The index of the first occurrence of `item`, starting from pos.
615 # Return -1 if `item` is not found.
616 # Comparison is done with `==`.
618 # var a = [10,20,30,10,20,30]
619 # assert a.index_of_from(20, 3) == 4
620 # assert a.index_of_from(20, 4) == 4
621 # assert a.index_of_from(20, 5) == -1
622 fun index_of_from
(item
: E
, pos
: Int): Int
627 if p
>=pos
and i
.item
== item
then return i
.index
634 # The index of the last occurrence of `item` starting from `pos` and decrementing.
635 # Return -1 if `item` is not found.
636 # Comparison is done with `==`.
638 # var a = [10,20,30,10,20,30]
639 # assert a.last_index_of_from(20, 2) == 1
640 # assert a.last_index_of_from(20, 1) == 1
641 # assert a.last_index_of_from(20, 0) == -1
642 fun last_index_of_from
(item
: E
, pos
: Int): Int
649 if i
.item
== item
then res
= p
656 # Two sequences are equals if they have the same items in the same order.
658 # var a = new List[Int]
662 # assert a == [1,2,3]
663 # assert a != [1,3,2]
666 if not o
isa SequenceRead[nullable Object] then return false
668 if o
.length
!= l
then return false
671 if self[i
] != o
[i
] then return false
677 # Because of the law between `==` and `hash`, `hash` is redefined to be the sum of the hash of the elements
681 for e
in self do res
+= res
.hash
685 redef fun iterator
: IndexedIterator[E
] is abstract
687 # Gets a new Iterator starting at position `pos`
689 # var iter = [10,20,30,40,50].iterator_from(2)
690 # assert iter.to_a == [30, 40, 50]
691 fun iterator_from
(pos
: Int): IndexedIterator[E
]
694 while pos
> 0 and res
.is_ok
do
701 # Gets an iterator starting at the end and going backwards
703 # var reviter = [1,2,3].reverse_iterator
704 # assert reviter.to_a == [3,2,1]
705 fun reverse_iterator
: IndexedIterator[E
] is abstract
707 # Gets an iterator on the chars of self starting from `pos`
709 # var reviter = [10,20,30,40,50].reverse_iterator_from(2)
710 # assert reviter.to_a == [30,20,10]
711 fun reverse_iterator_from
(pos
: Int): IndexedIterator[E
]
713 var res
= reverse_iterator
714 while pos
> 0 and res
.is_ok
do
722 # Sequence are indexed collection.
723 # The first item is 0. The last is `length-1`.
724 interface Sequence[E
]
725 super SequenceRead[E
]
726 super SimpleCollection[E
]
728 # Set the first item.
729 # Is equivalent with `self[0] = item`.
733 # assert a == [10,2,3]
735 do self[0] = item
end
738 # Is equivalent with `self[length-1] = item`.
742 # assert a == [1,2,10]
744 # If the sequence is empty, `last=` is equivalent with `self[0]=` (thus with `first=`)
746 # var b = new Array[Int]
759 # A synonym of `push`
760 redef fun add
(e
) do push
(e
)
762 # Add an item after the last one.
767 # assert a == [1,2,3,10,20]
768 fun push
(e
: E
) is abstract
770 # Add each item of `coll` after the last.
774 # assert a == [1,2,3,7,8,9]
775 fun append
(coll
: Collection[E
]) do for i
in coll
do push
(i
)
777 # Remove the last item.
784 # REQUIRE `not is_empty`
785 fun pop
: E
is abstract
787 # Add an item before the first one.
792 # assert a == [20,10,1,2,3]
793 fun unshift
(e
: E
) is abstract
795 # Remove the first item.
796 # The second item thus become the first.
799 # assert a.shift == 1
800 # assert a.shift == 2
803 # REQUIRE `not is_empty`
804 fun shift
: E
is abstract
806 # Set the `item` at `index`.
810 # assert a == [10,200,30]
812 # like with `[]`, index should be between `0` and `length-1`
813 # However, if `index==length`, `[]=` works like `push`.
816 # assert a == [10,200,30,400]
818 # REQUIRE `index >= 0 and index <= length`
819 fun []=(index
: Int, item
: E
) is abstract
821 # Insert an element at a given position, following elements are shifted.
823 # var a = [10, 20, 30, 40]
825 # assert a == [10, 20, 100, 30, 40]
827 # REQUIRE `index >= 0 and index < length`
828 # ENSURE `self[index] == item`
829 fun insert
(item
: E
, index
: Int) is abstract
831 # Remove the item at `index` and shift all following elements
835 # assert a == [10,30]
837 # REQUIRE `index >= 0 and index < length`
838 fun remove_at
(index
: Int) is abstract
841 # Iterators on indexed collections.
842 interface IndexedIterator[E
]
844 # The index of the current item.
845 fun index
: Int is abstract
848 # Associative arrays that internally uses couples to represent each (key, value) pairs.
849 # This is an helper class that some specific implementation of Map may implements.
850 interface CoupleMap[K
: Object, E
]
853 # Return the couple of the corresponding key
854 # Return null if the key is no associated element
855 protected fun couple_at
(key
: K
): nullable Couple[K
, E
] is abstract
857 # Return a new iteralot on all couples
858 # Used to provide `iterator` and others
859 protected fun couple_iterator
: Iterator[Couple[K
,E
]] is abstract
861 redef fun iterator
do return new CoupleMapIterator[K
,E
](couple_iterator
)
865 var c
= couple_at
(key
)
867 return provide_default_value
(key
)
874 # Iterator on CoupleMap
876 # Actually it is a wrapper around an iterator of the internal array of the map.
877 private class CoupleMapIterator[K
: Object, E
]
878 super MapIterator[K
, E
]
879 redef fun item
do return _iter
.item
.second
881 #redef fun item=(e) do _iter.item.second = e
883 redef fun key
do return _iter
.item
.first
885 redef fun is_ok
do return _iter
.is_ok
892 var _iter
: Iterator[Couple[K
,E
]]
894 init(i
: Iterator[Couple[K
,E
]]) do _iter
= i
897 # Some tools ###################################################################
899 # Two objects in a simple structure.
902 # The first element of the couple.
903 var first
: F
writable
905 # The second element of the couple.
906 var second
: S
writable
908 # Create a new instance with a first and a second object.