519279778217b7d87f276f6e72064860515afa5b
[nit.git] / lib / core / collection / abstract_collection.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 #
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
11 # another product.
12
13 # Abstract collection classes and services.
14 #
15 # TODO specify the behavior on iterators when collections are modified.
16 module abstract_collection
17
18 import kernel
19
20 # The root of the collection hierarchy.
21 #
22 # Collections modelize finite groups of objects, called elements.
23 #
24 # The specific behavior and representation of collections is determined
25 # by the subclasses of the hierarchy.
26 #
27 # The main service of Collection is to provide a stable `iterator`
28 # method usable to retrieve all the elements of the collection.
29 #
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.
34 #
35 # Because of the `iterator` method, Collections instances can use
36 # the `for` control structure.
37 #
38 # ~~~nitish
39 # var x: Collection[U]
40 # # ...
41 # for u in x do
42 # # u is a U
43 # # ...
44 # end
45 # ~~~
46 #
47 # that is equivalent with the following:
48 #
49 # ~~~nitish
50 # var x: Collection[U]
51 # # ...
52 # var i = x.iterator
53 # while i.is_ok do
54 # var u = i.item # u is a U
55 # # ...
56 # i.next
57 # end
58 # ~~~
59 interface Collection[E]
60 # Get a new iterator on the collection.
61 fun iterator: Iterator[E] is abstract
62
63 # Is there no item in the collection?
64 #
65 # assert [1,2,3].is_empty == false
66 # assert [1..1[.is_empty == true
67 fun is_empty: Bool do return length == 0
68
69 # Alias for `not is_empty`.
70 #
71 # Some people prefer to have conditions grammatically easier to read.
72 #
73 # assert [1,2,3].not_empty == true
74 # assert [1..1[.not_empty == false
75 fun not_empty: Bool do return not self.is_empty
76
77 # Number of items in the collection.
78 #
79 # assert [10,20,30].length == 3
80 # assert [20..30[.length == 10
81 fun length: Int
82 do
83 var nb = 0
84 for i in self do nb += 1
85 return nb
86 end
87
88 # Is `item` in the collection ?
89 # Comparisons are done with ==
90 #
91 # assert [1,2,3].has(2) == true
92 # assert [1,2,3].has(9) == false
93 # assert [1..5[.has(2) == true
94 # assert [1..5[.has(9) == false
95 fun has(item: nullable Object): Bool
96 do
97 for i in self do if i == item then return true
98 return false
99 end
100
101 # Is the collection contain only `item`?
102 # Comparisons are done with ==
103 # Return true if the collection is empty.
104 #
105 # assert [1,1,1].has_only(1) == true
106 # assert [1,2,3].has_only(1) == false
107 # assert [1..1].has_only(1) == true
108 # assert [1..3].has_only(1) == false
109 # assert [3..3[.has_only(1) == true # empty collection
110 #
111 # ENSURE `is_empty implies result == true`
112 fun has_only(item: nullable Object): Bool
113 do
114 for i in self do if i != item then return false
115 return true
116 end
117
118 # How many occurrences of `item` are in the collection?
119 # Comparisons are done with ==
120 #
121 # assert [10,20,10].count(10) == 2
122 fun count(item: nullable Object): Int
123 do
124 var nb = 0
125 for i in self do if i == item then nb += 1
126 return nb
127 end
128
129 # Return the first item of the collection
130 #
131 # assert [1,2,3].first == 1
132 fun first: E
133 do
134 assert length > 0
135 return iterator.item
136 end
137
138 # Does the collection contain at least each element of `other`?
139 #
140 # assert [1,3,4,2].has_all([1..2]) == true
141 # assert [1,3,4,2].has_all([1..5]) == false
142 #
143 # Repeated elements in the collections are not considered.
144 #
145 # assert [1,1,1].has_all([1]) == true
146 # assert [1..5].has_all([1,1,1]) == true
147 #
148 # Note that the default implementation is general and correct for any lawful Collections.
149 # It is memory-efficient but relies on `has` so may be CPU-inefficient for some kind of collections.
150 fun has_all(other: Collection[nullable Object]): Bool
151 do
152 for x in other do if not has(x) then return false
153 return true
154 end
155
156 # Does the collection contain exactly all the elements of `other`?
157 #
158 # The same elements must be present in both `self` and `other`,
159 # but the order of the elements in the collections are not considered.
160 #
161 # assert [1..3].has_exactly([3,1,2]) == true # the same elements
162 # assert [1..3].has_exactly([3,1]) == false # 2 is not in the array
163 # assert [1..2].has_exactly([3,1,2]) == false # 3 is not in the range
164 #
165 # Repeated elements must be present in both collections in the same amount.
166 # So basically it is a multi-set comparison.
167 #
168 # assert [1,2,3,2].has_exactly([1,2,2,3]) == true # the same elements
169 # assert [1,2,3,2].has_exactly([1,2,3]) == false # more 2 in the first array
170 # assert [1,2,3].has_exactly([1,2,2,3]) == false # more 2 in the second array
171 #
172 # Note that the default implementation is general and correct for any lawful Collections.
173 # It is memory-efficient but relies on `count` so may be CPU-inefficient for some kind of collections.
174 fun has_exactly(other: Collection[nullable Object]): Bool
175 do
176 if length != other.length then return false
177 for e in self do if self.count(e) != other.count(e) then return false
178 return true
179 end
180 end
181
182 # Iterators generate a series of elements, one at a time.
183 #
184 # They are mainly used with collections and obtained from `Collection::iterator`.
185 interface Iterator[E]
186 # The current item.
187 # Require `is_ok`.
188 fun item: E is abstract
189
190 # Jump to the next item.
191 # Require `is_ok`.
192 fun next is abstract
193
194 # Jump to the next item `step` times.
195 #
196 # ~~~
197 # var i = [11, 22, 33, 44].iterator
198 # assert i.item == 11
199 # i.next_by 2
200 # assert i.item == 33
201 # ~~~
202 #
203 # `next_by` should be used instead of looping on `next` because is takes care
204 # of stopping if the end of iteration is reached prematurely whereas a loop of
205 # `next` will abort because of the precondition on `is_ok`.
206 #
207 # ~~~
208 # i.next_by 100
209 # assert not i.is_ok
210 # ~~~
211 #
212 # If `step` is negative, this method aborts.
213 # But specific subclasses can change this and do something more meaningful instead.
214 #
215 # Require `is_ok`
216 fun next_by(step: Int)
217 do
218 assert step >= 0
219 while is_ok and step > 0 do
220 next
221 step -= 1
222 end
223 end
224
225 # Is there a current item ?
226 fun is_ok: Bool is abstract
227
228 # Iterate over `self`
229 fun iterator: Iterator[E] do return self
230
231 # Post-iteration hook.
232 #
233 # Used to inform `self` that the iteration is over.
234 # Specific iterators can use this to free some resources.
235 #
236 # Is automatically invoked at the end of `for` structures.
237 #
238 # Do nothing by default.
239 fun finish do end
240
241 # A decorator around `self` that advance self a given number of steps instead of one.
242 #
243 # ~~~
244 # var i = [11, 22, 33, 44, 55].iterator
245 # var i2 = i.to_step(2)
246 #
247 # assert i2.item == 11
248 # i2.next
249 # assert i2.item == 33
250 #
251 # assert i.item == 33
252 # ~~~
253 fun to_step(step: Int): Iterator[E] do return new StepIterator[E](self, step)
254 end
255
256 # A basic helper class to specialize specific Iterator decorators
257 abstract class IteratorDecorator[E]
258 super Iterator[E]
259
260 # The underling iterator
261 protected var real: Iterator[E]
262
263 redef fun is_ok do return real.is_ok
264 redef fun item do return real.item
265 redef fun finish do real.finish
266 redef fun next do real.next
267 redef fun next_by(step) do real.next_by(step)
268 end
269
270 # A decorator that advance a given number of steps
271 private class StepIterator[E]
272 super IteratorDecorator[E]
273 var step: Int
274
275 redef fun next do real.next_by(step)
276 redef fun next_by(step) do real.next_by(step * self.step)
277 end
278
279 # A collection that contains only one item.
280 #
281 # Used to pass arguments by reference.
282 #
283 # Also used when one want to give a single element when a full
284 # collection is expected
285 class Ref[E]
286 super Collection[E]
287
288 redef fun first do return item
289
290 redef fun is_empty do return false
291
292 redef fun length do return 1
293
294 redef fun has(an_item) do return item == an_item
295
296 redef fun has_only(an_item) do return item == an_item
297
298 redef fun count(an_item)
299 do
300 if item == an_item then
301 return 1
302 else
303 return 0
304 end
305 end
306
307 redef fun iterator do return new RefIterator[E](self)
308
309 # The stored item
310 var item: E is writable
311 end
312
313 # This iterator is quite stupid since it is used for only one item.
314 private class RefIterator[E]
315 super Iterator[E]
316 redef fun item do return _container.item
317
318 redef fun next do is_ok = false
319
320 redef var is_ok = true
321
322 var container: Ref[E]
323 end
324
325 # Items can be removed from this collection
326 interface RemovableCollection[E]
327 super Collection[E]
328
329 # Remove all items
330 #
331 # var a = [1,2,3]
332 # a.clear
333 # assert a.length == 0
334 #
335 # ENSURE `is_empty`
336 fun clear is abstract
337
338 # Remove an occurrence of `item`
339 #
340 # var a = [1,2,3,1,2,3]
341 # a.remove 2
342 # assert a == [1,3,1,2,3]
343 fun remove(item: nullable Object) is abstract
344
345 # Remove all occurrences of `item`
346 #
347 # var a = [1,2,3,1,2,3]
348 # a.remove_all 2
349 # assert a == [1,3,1,3]
350 fun remove_all(item: nullable Object) do while has(item) do remove(item)
351 end
352
353 # Items can be added to these collections.
354 interface SimpleCollection[E]
355 super RemovableCollection[E]
356
357 # Add an item in a collection.
358 #
359 # var a = [1,2]
360 # a.add 3
361 # assert a.has(3) == true
362 # assert a.has(10) == false
363 #
364 # Ensure col.has(item)
365 fun add(item: E) is abstract
366
367 # Add each item of `coll`.
368 # var a = [1,2]
369 # a.add_all([3..5])
370 # assert a.has(4) == true
371 # assert a.has(10) == false
372 fun add_all(coll: Collection[E]) do for i in coll do add(i)
373 end
374
375 # Abstract sets.
376 #
377 # Set is a collection without duplicates (according to `==`)
378 #
379 # var s: Set[String] = new ArraySet[String]
380 # var a = "Hello"
381 # var b = "Hel" + "lo"
382 # # ...
383 # s.add(a)
384 # assert s.has(b) == true
385 interface Set[E]
386 super SimpleCollection[E]
387
388 redef fun has_only(item)
389 do
390 var l = length
391 if l == 1 then
392 return has(item)
393 else if l == 0 then
394 return true
395 else
396 return false
397 end
398 end
399
400 # Only 0 or 1
401 redef fun count(item)
402 do
403 if has(item) then
404 return 1
405 else
406 return 0
407 end
408 end
409
410 # Synonym of remove since there is only one item
411 redef fun remove_all(item) do remove(item)
412
413 # Equality is defined on set and means that each set contains the same elements
414 redef fun ==(other)
415 do
416 if not other isa Set[nullable Object] then return false
417 if other.length != length then return false
418 return has_all(other)
419 end
420
421 # Because of the law between `==` and `hash`, `hash` is redefined to be the sum of the hash of the elements
422 redef fun hash
423 do
424 # 23 is a magic number empirically determined to be not so bad.
425 var res = 23 + length
426 # Note: the order of the elements must not change the hash value.
427 # So, unlike usual hash functions, the accumulator is not combined with itself.
428 for e in self do res += e.hash
429 return res
430 end
431
432 # Returns the union of this set with the `other` set
433 fun union(other: Set[E]): Set[E]
434 do
435 var nhs = new_set
436 nhs.add_all self
437 nhs.add_all other
438 return nhs
439 end
440
441 # Returns the intersection of this set with the `other` set
442 fun intersection(other: Set[E]): Set[E]
443 do
444 var nhs = new_set
445 for v in self do if other.has(v) then nhs.add(v)
446 return nhs
447 end
448
449 # Returns a new instance of `Set`.
450 #
451 # Depends on the subclass, mainly used for copy services
452 # like `union` or `intersection`.
453 protected fun new_set: Set[E] is abstract
454 end
455
456 # MapRead are abstract associative collections: `key` -> `item`.
457 interface MapRead[K, V]
458 # Get the item at `key`
459 #
460 # var x = new HashMap[String, Int]
461 # x["four"] = 4
462 # assert x["four"] == 4
463 # # assert x["five"] #=> abort
464 #
465 # If the key is not in the map, `provide_default_value` is called (that aborts by default)
466 # See `get_or_null` and `get_or_default` for safe variations.
467 fun [](key: nullable Object): V is abstract
468
469 # Get the item at `key` or null if `key` is not in the map.
470 #
471 # var x = new HashMap[String, Int]
472 # x["four"] = 4
473 # assert x.get_or_null("four") == 4
474 # assert x.get_or_null("five") == null
475 #
476 # Note: use `has_key` and `[]` if you need the distinction between a key associated with null, and no key.
477 fun get_or_null(key: nullable Object): nullable V
478 do
479 if has_key(key) then return self[key]
480 return null
481 end
482
483 # Get the item at `key` or return `default` if not in map
484 #
485 # var x = new HashMap[String, Int]
486 # x["four"] = 4
487 # assert x.get_or_default("four", 40) == 4
488 # assert x.get_or_default("five", 50) == 50
489 #
490 fun get_or_default(key: nullable Object, default: V): V
491 do
492 if has_key(key) then return self[key]
493 return default
494 end
495
496 # Is there an item associated with `key`?
497 #
498 # var x = new HashMap[String, Int]
499 # x["four"] = 4
500 # assert x.has_key("four") == true
501 # assert x.has_key("five") == false
502 #
503 # By default it is a synonymous to `keys.has` but could be redefined with a direct implementation.
504 fun has_key(key: nullable Object): Bool do return self.keys.has(key)
505
506 # Get a new iterator on the map.
507 fun iterator: MapIterator[K, V] is abstract
508
509 # Return the point of view of self on the values only.
510 # Note that `self` and `values` are views on the same data;
511 # therefore any modification of one is visible on the other.
512 #
513 # var x = new HashMap[String, Int]
514 # x["four"] = 4
515 # assert x.values.has(4) == true
516 # assert x.values.has(5) == false
517 fun values: Collection[V] is abstract
518
519 # Return the point of view of self on the keys only.
520 # Note that `self` and `keys` are views on the same data;
521 # therefore any modification of one is visible on the other.
522 #
523 # var x = new HashMap[String, Int]
524 # x["four"] = 4
525 # assert x.keys.has("four") == true
526 # assert x.keys.has("five") == false
527 fun keys: Collection[K] is abstract
528
529 # Is there no item in the collection?
530 #
531 # var x = new HashMap[String, Int]
532 # assert x.is_empty == true
533 # x["four"] = 4
534 # assert x.is_empty == false
535 fun is_empty: Bool is abstract
536
537 # Alias for `not is_empty`.
538 #
539 # Some people prefer to have conditions grammatically easier to read.
540 #
541 # var map = new HashMap[String, Int]
542 # assert map.not_empty == false
543 # map["one"] = 1
544 # assert map.not_empty == true
545 fun not_empty: Bool do return not self.is_empty
546
547 # Number of items in the collection.
548 #
549 # var x = new HashMap[String, Int]
550 # assert x.length == 0
551 # x["four"] = 4
552 # assert x.length == 1
553 # x["five"] = 5
554 # assert x.length == 2
555 fun length: Int is abstract
556
557 # Called by the underling implementation of `[]` to provide a default value when a `key` has no value
558 # By default the behavior is to abort.
559 #
560 # Note: the value is returned *as is*, implementations may want to store the value in the map before returning it
561 # @toimplement
562 protected fun provide_default_value(key: nullable Object): V do abort
563
564 # Does `self` and `other` have the same keys associated with the same values?
565 #
566 # ~~~
567 # var a = new HashMap[String, Int]
568 # var b = new ArrayMap[Object, Numeric]
569 # assert a == b
570 # a["one"] = 1
571 # assert a != b
572 # b["one"] = 1
573 # assert a == b
574 # b["one"] = 2
575 # assert a != b
576 # ~~~
577 redef fun ==(other)
578 do
579 if not other isa MapRead[nullable Object, nullable Object] then return false
580 if other.length != self.length then return false
581 for k, v in self do
582 if not other.has_key(k) then return false
583 if other[k] != v then return false
584 end
585 return true
586 end
587
588 # A hashcode based on the hashcode of the keys and the values.
589 #
590 # ~~~
591 # var a = new HashMap[String, Int]
592 # var b = new ArrayMap[Object, Numeric]
593 # a["one"] = 1
594 # b["one"] = 1
595 # assert a.hash == b.hash
596 # ~~~
597 redef fun hash
598 do
599 var res = length
600 for k, v in self do
601 if k != null then res += k.hash * 7
602 if v != null then res += v.hash * 11
603 end
604 return res
605 end
606 end
607
608 # Maps are associative collections: `key` -> `item`.
609 #
610 # The main operator over maps is [].
611 #
612 # var map: Map[String, Int] = new ArrayMap[String, Int]
613 # # ...
614 # map["one"] = 1 # Associate 'one' to '1'
615 # map["two"] = 2 # Associate 'two' to '2'
616 # assert map["one"] == 1
617 # assert map["two"] == 2
618 #
619 # Instances of maps can be used with the for structure
620 #
621 # for key, value in map do
622 # assert (key == "one" and value == 1) or (key == "two" and value == 2)
623 # end
624 #
625 # The keys and values in the map can also be manipulated directly with the `keys` and `values` methods.
626 #
627 # assert map.keys.has("one") == true
628 # assert map.keys.has("tree") == false
629 # assert map.values.has(1) == true
630 # assert map.values.has(3) == false
631 #
632 interface Map[K, V]
633 super MapRead[K, V]
634
635 # Set the `value` at `key`.
636 #
637 # Values can then get retrieved with `[]`.
638 #
639 # var x = new HashMap[String, Int]
640 # x["four"] = 4
641 # assert x["four"] == 4
642 #
643 # If the key was associated with a value, this old value is discarded
644 # and replaced with the new one.
645 #
646 # x["four"] = 40
647 # assert x["four"] == 40
648 # assert x.values.has(4) == false
649 #
650 fun []=(key: K, value: V) is abstract
651
652 # Add each (key,value) of `map` into `self`.
653 # If a same key exists in `map` and `self`, then the value in self is discarded.
654 #
655 # It is the analogous of `SimpleCollection::add_all`
656 #
657 # var x = new HashMap[String, Int]
658 # x["four"] = 4
659 # x["five"] = 5
660 # var y = new HashMap[String, Int]
661 # y["four"] = 40
662 # y["nine"] = 90
663 # x.recover_with y
664 # assert x["four"] == 40
665 # assert x["five"] == 5
666 # assert x["nine"] == 90
667 fun recover_with(map: MapRead[K, V])
668 do
669 var i = map.iterator
670 while i.is_ok do
671 self[i.key] = i.item
672 i.next
673 end
674 end
675
676 # Remove all items
677 #
678 # var x = new HashMap[String, Int]
679 # x["four"] = 4
680 # x.clear
681 # assert x.keys.has("four") == false
682 #
683 # ENSURE `is_empty`
684 fun clear is abstract
685
686 redef fun values: RemovableCollection[V] is abstract
687
688 redef fun keys: RemovableCollection[K] is abstract
689 end
690
691 # Iterators for Map.
692 interface MapIterator[K, V]
693 # The current item.
694 # Require `is_ok`.
695 fun item: V is abstract
696
697 # The key of the current item.
698 # Require `is_ok`.
699 fun key: K is abstract
700
701 # Jump to the next item.
702 # Require `is_ok`.
703 fun next is abstract
704
705 # Is there a current item ?
706 fun is_ok: Bool is abstract
707
708 # Set a new `item` at `key`.
709 #fun item=(item: E) is abstract
710
711 # Post-iteration hook.
712 #
713 # Used to inform `self` that the iteration is over.
714 # Specific iterators can use this to free some resources.
715 #
716 # Is automatically invoked at the end of `for` structures.
717 #
718 # Do nothing by default.
719 fun finish do end
720 end
721
722 # Iterator on a 'keys' point of view of a map
723 class MapKeysIterator[K, V]
724 super Iterator[K]
725 # The original iterator
726 var original_iterator: MapIterator[K, V]
727
728 redef fun is_ok do return self.original_iterator.is_ok
729 redef fun next do self.original_iterator.next
730 redef fun item do return self.original_iterator.key
731 end
732
733 # Iterator on a 'values' point of view of a map
734 class MapValuesIterator[K, V]
735 super Iterator[V]
736 # The original iterator
737 var original_iterator: MapIterator[K, V]
738
739 redef fun is_ok do return self.original_iterator.is_ok
740 redef fun next do self.original_iterator.next
741 redef fun item do return self.original_iterator.item
742 end
743
744 # Sequences are indexed collections.
745 # The first item is 0. The last is `length-1`.
746 #
747 # The order is the main caracteristic of sequence
748 # and all concrete implementation of sequences are basically interchangeable.
749 interface SequenceRead[E]
750 super Collection[E]
751
752 # Get the first item.
753 # Is equivalent with `self[0]`.
754 #
755 # var a = [1,2,3]
756 # assert a.first == 1
757 #
758 # REQUIRE `not is_empty`
759 redef fun first
760 do
761 assert not_empty: not is_empty
762 return self[0]
763 end
764
765 # Return the index-th element of the sequence.
766 # The first element is 0 and the last is `length-1`
767 # If index is invalid, the program aborts
768 #
769 # var a = [10,20,30]
770 # assert a[0] == 10
771 # assert a[1] == 20
772 # assert a[2] == 30
773 #
774 # REQUIRE `index >= 0 and index < length`
775 fun [](index: Int): E is abstract
776
777 # Get the last item.
778 # Is equivalent with `self[length-1]`.
779 #
780 # var a = [1,2,3]
781 # assert a.last == 3
782 #
783 # REQUIRE `not is_empty`
784 fun last: E
785 do
786 assert not_empty: not is_empty
787 return self[length-1]
788 end
789
790 # The index of the first occurrence of `item`.
791 # Return -1 if `item` is not found.
792 # Comparison is done with `==`.
793 #
794 # var a = [10,20,30,10,20,30]
795 # assert a.index_of(20) == 1
796 # assert a.index_of(40) == -1
797 fun index_of(item: nullable Object): Int do return index_of_from(item, 0)
798
799 # The index of the last occurrence of `item`.
800 # Return -1 if `item` is not found.
801 # Comparison is done with `==`.
802 #
803 # var a = [10,20,30,10,20,30]
804 # assert a.last_index_of(20) == 4
805 # assert a.last_index_of(40) == -1
806 fun last_index_of(item: nullable Object): Int do return last_index_of_from(item, length-1)
807
808 # The index of the first occurrence of `item`, starting from pos.
809 # Return -1 if `item` is not found.
810 # Comparison is done with `==`.
811 #
812 # var a = [10,20,30,10,20,30]
813 # assert a.index_of_from(20, 3) == 4
814 # assert a.index_of_from(20, 4) == 4
815 # assert a.index_of_from(20, 5) == -1
816 fun index_of_from(item: nullable Object, pos: Int): Int
817 do
818 var p = 0
819 var i = iterator
820 while i.is_ok do
821 if p>=pos and i.item == item then return i.index
822 i.next
823 p += 1
824 end
825 return -1
826 end
827
828 # The index of the last occurrence of `item` starting from `pos` and decrementing.
829 # Return -1 if `item` is not found.
830 # Comparison is done with `==`.
831 #
832 # var a = [10,20,30,10,20,30]
833 # assert a.last_index_of_from(20, 2) == 1
834 # assert a.last_index_of_from(20, 1) == 1
835 # assert a.last_index_of_from(20, 0) == -1
836 fun last_index_of_from(item: nullable Object, pos: Int): Int
837 do
838 var res = -1
839 var p = 0
840 var i = iterator
841 while i.is_ok do
842 if p>pos then break
843 if i.item == item then res = p
844 i.next
845 p += 1
846 end
847 return res
848 end
849
850 # Two sequences are equals if they have the same items in the same order.
851 #
852 # var a = new List[Int]
853 # a.add(1)
854 # a.add(2)
855 # a.add(3)
856 # assert a == [1,2,3]
857 # assert a != [1,3,2]
858 redef fun ==(o)
859 do
860 if not o isa SequenceRead[nullable Object] then return false
861 var l = length
862 if o.length != l then return false
863 var i = 0
864 while i < l do
865 if self[i] != o[i] then return false
866 i += 1
867 end
868 return true
869 end
870
871 # Because of the law between `==` and `hash`, `hash` is redefined to be the sum of the hash of the elements
872 redef fun hash
873 do
874 # The 17 and 2/3 magic numbers were determined empirically.
875 # Note: the standard hash functions djb2, sbdm and fnv1 were also
876 # tested but were comparable (or worse).
877 var res = 17 + length
878 for e in self do
879 res = res * 3 / 2
880 if e != null then res += e.hash
881 end
882 return res
883 end
884
885 redef fun iterator: IndexedIterator[E] is abstract
886
887 # Gets a new Iterator starting at position `pos`
888 #
889 # var iter = [10,20,30,40,50].iterator_from(2)
890 # assert iter.to_a == [30, 40, 50]
891 fun iterator_from(pos: Int): IndexedIterator[E]
892 do
893 var res = iterator
894 while pos > 0 and res.is_ok do
895 res.next
896 pos -= 1
897 end
898 return res
899 end
900
901 # Gets an iterator starting at the end and going backwards
902 #
903 # var reviter = [1,2,3].reverse_iterator
904 # assert reviter.to_a == [3,2,1]
905 fun reverse_iterator: IndexedIterator[E] is abstract
906
907 # Gets an iterator on the chars of self starting from `pos`
908 #
909 # var reviter = [10,20,30,40,50].reverse_iterator_from(2)
910 # assert reviter.to_a == [30,20,10]
911 fun reverse_iterator_from(pos: Int): IndexedIterator[E]
912 do
913 var res = reverse_iterator
914 while pos > 0 and res.is_ok do
915 res.next
916 pos -= 1
917 end
918 return res
919 end
920 end
921
922 # Sequence are indexed collection.
923 # The first item is 0. The last is `length-1`.
924 interface Sequence[E]
925 super SequenceRead[E]
926 super SimpleCollection[E]
927
928 # Set the first item.
929 # Is equivalent with `self[0] = item`.
930 #
931 # var a = [1,2,3]
932 # a.first = 10
933 # assert a == [10,2,3]
934 fun first=(item: E)
935 do self[0] = item end
936
937 # Set the last item.
938 # Is equivalent with `self[length-1] = item`.
939 #
940 # var a = [1,2,3]
941 # a.last = 10
942 # assert a == [1,2,10]
943 #
944 # If the sequence is empty, `last=` is equivalent with `self[0]=` (thus with `first=`)
945 #
946 # var b = new Array[Int]
947 # b.last = 10
948 # assert b == [10]
949 fun last=(item: E)
950 do
951 var l = length
952 if l > 0 then
953 self[l-1] = item
954 else
955 self[0] = item
956 end
957 end
958
959 # A synonym of `push`
960 redef fun add(e) do push(e)
961
962 # Add an item after the last one.
963 #
964 # var a = [1,2,3]
965 # a.push(10)
966 # a.push(20)
967 # assert a == [1,2,3,10,20]
968 fun push(e: E) is abstract
969
970 # Add each item of `coll` after the last.
971 #
972 # var a = [1,2,3]
973 # a.append([7..9])
974 # assert a == [1,2,3,7,8,9]
975 #
976 # Alias of `add_all`
977 fun append(coll: Collection[E]) do add_all(coll)
978
979 # Remove the last item.
980 #
981 # var a = [1,2,3]
982 # assert a.pop == 3
983 # assert a.pop == 2
984 # assert a == [1]
985 #
986 # REQUIRE `not is_empty`
987 fun pop: E is abstract
988
989 # Add an item before the first one.
990 #
991 # var a = [1,2,3]
992 # a.unshift(10)
993 # a.unshift(20)
994 # assert a == [20,10,1,2,3]
995 fun unshift(e: E) is abstract
996
997 # Add all items of `coll` before the first one.
998 #
999 # var a = [1,2,3]
1000 # a.prepend([7..9])
1001 # assert a == [7,8,9,1,2,3]
1002 #
1003 # Alias of `insert_at(coll, 0)`
1004 fun prepend(coll: Collection[E]) do insert_all(coll, 0)
1005
1006 # Remove the first item.
1007 # The second item thus become the first.
1008 #
1009 # var a = [1,2,3]
1010 # assert a.shift == 1
1011 # assert a.shift == 2
1012 # assert a == [3]
1013 #
1014 # REQUIRE `not is_empty`
1015 fun shift: E is abstract
1016
1017 # Set the `item` at `index`.
1018 #
1019 # var a = [10,20,30]
1020 # a[1] = 200
1021 # assert a == [10,200,30]
1022 #
1023 # like with `[]`, index should be between `0` and `length-1`
1024 # However, if `index==length`, `[]=` works like `push`.
1025 #
1026 # a[3] = 400
1027 # assert a == [10,200,30,400]
1028 #
1029 # REQUIRE `index >= 0 and index <= length`
1030 fun []=(index: Int, item: E) is abstract
1031
1032 # Insert an element at a given position, following elements are shifted.
1033 #
1034 # var a = [10, 20, 30, 40]
1035 # a.insert(100, 2)
1036 # assert a == [10, 20, 100, 30, 40]
1037 #
1038 # REQUIRE `index >= 0 and index <= length`
1039 # ENSURE `self[index] == item`
1040 fun insert(item: E, index: Int) is abstract
1041
1042 # Insert all elements at a given position, following elements are shifted.
1043 #
1044 # var a = [10, 20, 30, 40]
1045 # a.insert_all([100..102], 2)
1046 # assert a == [10, 20, 100, 101, 102, 30, 40]
1047 #
1048 # REQUIRE `index >= 0 and index <= length`
1049 # ENSURE `self[index] == coll.first`
1050 fun insert_all(coll: Collection[E], index: Int)
1051 do
1052 assert index >= 0 and index < length
1053 if index == length then
1054 add_all(coll)
1055 end
1056 for c in coll do
1057 insert(c, index)
1058 index += 1
1059 end
1060 end
1061
1062 # Remove the item at `index` and shift all following elements
1063 #
1064 # var a = [10,20,30]
1065 # a.remove_at(1)
1066 # assert a == [10,30]
1067 #
1068 # REQUIRE `index >= 0 and index < length`
1069 fun remove_at(index: Int) is abstract
1070 end
1071
1072 # Iterators on indexed collections.
1073 interface IndexedIterator[E]
1074 super Iterator[E]
1075 # The index of the current item.
1076 fun index: Int is abstract
1077 end
1078
1079 # Associative arrays that internally uses couples to represent each (key, value) pairs.
1080 # This is an helper class that some specific implementation of Map may implements.
1081 interface CoupleMap[K, V]
1082 super Map[K, V]
1083
1084 # Return the couple of the corresponding key
1085 # Return null if the key is no associated element
1086 protected fun couple_at(key: nullable Object): nullable Couple[K, V] is abstract
1087
1088 # Return a new iteralot on all couples
1089 # Used to provide `iterator` and others
1090 protected fun couple_iterator: Iterator[Couple[K,V]] is abstract
1091
1092 redef fun iterator do return new CoupleMapIterator[K,V](couple_iterator)
1093
1094 redef fun [](key)
1095 do
1096 var c = couple_at(key)
1097 if c == null then
1098 return provide_default_value(key)
1099 else
1100 return c.second
1101 end
1102 end
1103
1104 redef fun has_key(key) do return couple_at(key) != null
1105 end
1106
1107 # Iterator on CoupleMap
1108 #
1109 # Actually it is a wrapper around an iterator of the internal array of the map.
1110 private class CoupleMapIterator[K, V]
1111 super MapIterator[K, V]
1112 redef fun item do return _iter.item.second
1113
1114 #redef fun item=(e) do _iter.item.second = e
1115
1116 redef fun key do return _iter.item.first
1117
1118 redef fun is_ok do return _iter.is_ok
1119
1120 redef fun next
1121 do
1122 _iter.next
1123 end
1124
1125 var iter: Iterator[Couple[K,V]]
1126 end
1127
1128 # Some tools ###################################################################
1129
1130 # Two objects in a simple structure.
1131 class Couple[F, S]
1132
1133 # The first element of the couple.
1134 var first: F is writable
1135
1136 # The second element of the couple.
1137 var second: S is writable
1138 end