lib/core/collection: add `CachedIterator` to factorize the logic of iterators with...
[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 if is_same_instance(other) then return true
153 var ol = other.length
154 var l = length
155 if ol == 0 then return true
156 if l == 0 then return false
157 if ol == 1 then return has(other.first)
158 for x in other do if not has(x) then return false
159 return true
160 end
161
162 # Does the collection contain exactly all the elements of `other`?
163 #
164 # The same elements must be present in both `self` and `other`,
165 # but the order of the elements in the collections are not considered.
166 #
167 # assert [1..3].has_exactly([3,1,2]) == true # the same elements
168 # assert [1..3].has_exactly([3,1]) == false # 2 is not in the array
169 # assert [1..2].has_exactly([3,1,2]) == false # 3 is not in the range
170 #
171 # Repeated elements must be present in both collections in the same amount.
172 # So basically it is a multi-set comparison.
173 #
174 # assert [1,2,3,2].has_exactly([1,2,2,3]) == true # the same elements
175 # assert [1,2,3,2].has_exactly([1,2,3]) == false # more 2 in the first array
176 # assert [1,2,3].has_exactly([1,2,2,3]) == false # more 2 in the second array
177 #
178 # Note that the default implementation is general and correct for any lawful Collections.
179 # It is memory-efficient but relies on `count` so may be CPU-inefficient for some kind of collections.
180 fun has_exactly(other: Collection[nullable Object]): Bool
181 do
182 if length != other.length then return false
183 for e in self do if self.count(e) != other.count(e) then return false
184 return true
185 end
186
187 # Does the collection contain at least one element of `other`?
188 #
189 # assert [1,3,4,2].has_any([1..10]) == true
190 # assert [1,3,4,2].has_any([5..10]) == false
191 #
192 # Note that the default implementation is general and correct for any lawful Collections.
193 # It is memory-efficient but relies on `has` so may be CPU-inefficient for some kind of collections.
194 fun has_any(other: Collection[nullable Object]): Bool
195 do
196 for o in other do
197 if has(o) then return true
198 end
199 return false
200 end
201 end
202
203 # Iterators generate a series of elements, one at a time.
204 #
205 # They are mainly used with collections and obtained from `Collection::iterator`.
206 interface Iterator[E]
207 # The current item.
208 # Require `is_ok`.
209 fun item: E is abstract
210
211 # Jump to the next item.
212 # Require `is_ok`.
213 fun next is abstract
214
215 # Jump to the next item `step` times.
216 #
217 # ~~~
218 # var i = [11, 22, 33, 44].iterator
219 # assert i.item == 11
220 # i.next_by 2
221 # assert i.item == 33
222 # ~~~
223 #
224 # `next_by` should be used instead of looping on `next` because is takes care
225 # of stopping if the end of iteration is reached prematurely whereas a loop of
226 # `next` will abort because of the precondition on `is_ok`.
227 #
228 # ~~~
229 # i.next_by 100
230 # assert not i.is_ok
231 # ~~~
232 #
233 # If `step` is negative, this method aborts.
234 # But specific subclasses can change this and do something more meaningful instead.
235 #
236 # Require `is_ok`
237 fun next_by(step: Int)
238 do
239 assert step >= 0
240 while is_ok and step > 0 do
241 next
242 step -= 1
243 end
244 end
245
246 # Is there a current item ?
247 fun is_ok: Bool is abstract
248
249 # Iterate over `self`
250 fun iterator: Iterator[E] do return self
251
252 # Pre-iteration hook.
253 #
254 # Used to inform `self` that the iteration is starting.
255 # Specific iterators can use this to prepare some resources.
256 #
257 # Is automatically invoked at the beginning of `for` structures.
258 #
259 # Do nothing by default.
260 fun start do end
261
262 # Post-iteration hook.
263 #
264 # Used to inform `self` that the iteration is over.
265 # Specific iterators can use this to free some resources.
266 #
267 # Is automatically invoked at the end of `for` structures.
268 #
269 # Do nothing by default.
270 fun finish do end
271
272 # A decorator around `self` that advance self a given number of steps instead of one.
273 #
274 # ~~~
275 # var i = [11, 22, 33, 44, 55].iterator
276 # var i2 = i.to_step(2)
277 #
278 # assert i2.item == 11
279 # i2.next
280 # assert i2.item == 33
281 #
282 # assert i.item == 33
283 # ~~~
284 fun to_step(step: Int): Iterator[E] do return new StepIterator[E](self, step)
285 end
286
287 # A basic helper class to specialize specific Iterator decorators
288 abstract class IteratorDecorator[E]
289 super Iterator[E]
290
291 # The underling iterator
292 protected var real: Iterator[E]
293
294 redef fun is_ok do return real.is_ok
295 redef fun item do return real.item
296 redef fun finish do real.finish
297 redef fun next do real.next
298 redef fun next_by(step) do real.next_by(step)
299 end
300
301 # A decorator that advance a given number of steps
302 private class StepIterator[E]
303 super IteratorDecorator[E]
304 var step: Int
305
306 redef fun next do real.next_by(step)
307 redef fun next_by(step) do real.next_by(step * self.step)
308 end
309
310 # An iterator that lazyly cache the current item.
311 #
312 # This class can be used as an helper to build simple iterator with a single and simplier `next_item` method.
313 # The only constraint is that `next_item` returns null on the last item, so `null` cannot be a valid element.
314 abstract class CachedIterator[E: Object]
315 super Iterator[E]
316
317 # Get the next item if any.
318 # Returns null if there is no next item.
319 fun next_item: nullable E is abstract
320
321 # The last item effectively read.
322 # `null` if on start, after a next of if no more items are available.
323 protected var cache: nullable E = null
324
325 # The current item, if any.
326 # If not, the cache is effectively filled (with `next_item`).
327 # Return `null` iff there is no more elements.
328 protected fun current_item: nullable E
329 do
330 var cache = self.cache
331 if cache != null then return cache
332 cache = next_item
333 self.cache = cache
334 return cache
335 end
336
337 redef fun item do return current_item.as(not null)
338
339 redef fun is_ok do return current_item != null
340
341 redef fun next do
342 # If needed, fill the cache (an consume the current element)
343 current_item
344 # Empty the cache (so the next element will be read)
345 cache = null
346 end
347 end
348
349 # A collection that contains only one item.
350 #
351 # Used to pass arguments by reference.
352 #
353 # Also used when one want to give a single element when a full
354 # collection is expected
355 class Ref[E]
356 super Collection[E]
357
358 redef fun first do return item
359
360 redef fun is_empty do return false
361
362 redef fun length do return 1
363
364 redef fun has(an_item) do return item == an_item
365
366 redef fun has_only(an_item) do return item == an_item
367
368 redef fun count(an_item)
369 do
370 if item == an_item then
371 return 1
372 else
373 return 0
374 end
375 end
376
377 redef fun iterator do return new RefIterator[E](self)
378
379 # The stored item
380 var item: E is writable
381 end
382
383 # This iterator is quite stupid since it is used for only one item.
384 private class RefIterator[E]
385 super Iterator[E]
386 redef fun item do return _container.item
387
388 redef fun next do is_ok = false
389
390 redef var is_ok = true
391
392 var container: Ref[E]
393 end
394
395 # Items can be removed from this collection
396 interface RemovableCollection[E]
397 super Collection[E]
398
399 # Remove all items
400 #
401 # var a = [1,2,3]
402 # a.clear
403 # assert a.length == 0
404 #
405 # ENSURE `is_empty`
406 fun clear is abstract
407
408 # Remove an occurrence of `item`
409 #
410 # var a = [1,2,3,1,2,3]
411 # a.remove 2
412 # assert a == [1,3,1,2,3]
413 fun remove(item: nullable Object) is abstract
414
415 # Remove all occurrences of `item`
416 #
417 # var a = [1,2,3,1,2,3]
418 # a.remove_all 2
419 # assert a == [1,3,1,3]
420 fun remove_all(item: nullable Object) do while has(item) do remove(item)
421 end
422
423 # Items can be added to these collections.
424 interface SimpleCollection[E]
425 super RemovableCollection[E]
426
427 # Add `item` to this collection.
428 #
429 # var a = [1,2]
430 # a.add 3
431 # assert a.has(3) == true
432 # assert a.has(10) == false
433 #
434 # Ensure col.has(item)
435 fun add(item: E) is abstract
436
437 # Add each item of `coll`.
438 #
439 # var a = [1,2]
440 # a.add_all([3..5])
441 # assert a.has(4) == true
442 # assert a.has(10) == false
443 fun add_all(coll: Collection[E]) do for i in coll do add(i)
444 end
445
446 # Abstract sets.
447 #
448 # Set is a collection without duplicates (according to `==`)
449 #
450 # var s: Set[String] = new ArraySet[String]
451 # var a = "Hello"
452 # var b = "Hel" + "lo"
453 # # ...
454 # s.add(a)
455 # assert s.has(b) == true
456 interface Set[E]
457 super SimpleCollection[E]
458 super Cloneable
459
460 redef fun has_only(item)
461 do
462 var l = length
463 if l == 1 then
464 return has(item)
465 else if l == 0 then
466 return true
467 else
468 return false
469 end
470 end
471
472 # Only 0 or 1
473 redef fun count(item)
474 do
475 if has(item) then
476 return 1
477 else
478 return 0
479 end
480 end
481
482 # Synonym of remove since there is only one item
483 redef fun remove_all(item) do remove(item)
484
485 # Equality is defined on set and means that each set contains the same elements
486 redef fun ==(other)
487 do
488 if not other isa Set[nullable Object] then return false
489 if other.length != length then return false
490 return has_all(other)
491 end
492
493 # Because of the law between `==` and `hash`, `hash` is redefined to be the sum of the hash of the elements
494 redef fun hash
495 do
496 # 23 is a magic number empirically determined to be not so bad.
497 var res = 23 + length
498 # Note: the order of the elements must not change the hash value.
499 # So, unlike usual hash functions, the accumulator is not combined with itself.
500 for e in self do
501 if e != null then res += e.hash
502 end
503 return res
504 end
505
506 # Returns the union of this set with the `other` set
507 fun union(other: Set[E]): Set[E]
508 do
509 var nhs = new_set
510 nhs.add_all self
511 nhs.add_all other
512 return nhs
513 end
514
515 # Returns the intersection of this set with the `other` set
516 fun intersection(other: Set[E]): Set[E]
517 do
518 var nhs = new_set
519 for v in self do if other.has(v) then nhs.add(v)
520 return nhs
521 end
522
523 redef fun clone do return union(self)
524
525 # Returns a new instance of `Set`.
526 #
527 # Depends on the subclass, mainly used for copy services
528 # like `union` or `intersection`.
529 protected fun new_set: Set[E] is abstract
530 end
531
532 # MapRead are abstract associative collections: `key` -> `item`.
533 interface MapRead[K, V]
534 # Get the item at `key`
535 #
536 # var x = new HashMap[String, Int]
537 # x["four"] = 4
538 # assert x["four"] == 4
539 # # assert x["five"] #=> abort
540 #
541 # If the key is not in the map, `provide_default_value` is called (that aborts by default)
542 # See `get_or_null` and `get_or_default` for safe variations.
543 fun [](key: nullable Object): V is abstract
544
545 # Get the item at `key` or null if `key` is not in the map.
546 #
547 # var x = new HashMap[String, Int]
548 # x["four"] = 4
549 # assert x.get_or_null("four") == 4
550 # assert x.get_or_null("five") == null
551 #
552 # Note: use `has_key` and `[]` if you need the distinction between a key associated with null, and no key.
553 fun get_or_null(key: nullable Object): nullable V
554 do
555 if has_key(key) then return self[key]
556 return null
557 end
558
559 # Get the item at `key` or return `default` if not in map
560 #
561 # var x = new HashMap[String, Int]
562 # x["four"] = 4
563 # assert x.get_or_default("four", 40) == 4
564 # assert x.get_or_default("five", 50) == 50
565 #
566 fun get_or_default(key: nullable Object, default: V): V
567 do
568 if has_key(key) then return self[key]
569 return default
570 end
571
572 # Is there an item associated with `key`?
573 #
574 # var x = new HashMap[String, Int]
575 # x["four"] = 4
576 # assert x.has_key("four") == true
577 # assert x.has_key("five") == false
578 #
579 # By default it is a synonymous to `keys.has` but could be redefined with a direct implementation.
580 fun has_key(key: nullable Object): Bool do return self.keys.has(key)
581
582 # Get a new iterator on the map.
583 fun iterator: MapIterator[K, V] is abstract
584
585 # Return the point of view of self on the values only.
586 # Note that `self` and `values` are views on the same data;
587 # therefore any modification of one is visible on the other.
588 #
589 # var x = new HashMap[String, Int]
590 # x["four"] = 4
591 # assert x.values.has(4) == true
592 # assert x.values.has(5) == false
593 fun values: Collection[V] is abstract
594
595 # Return the point of view of self on the keys only.
596 # Note that `self` and `keys` are views on the same data;
597 # therefore any modification of one is visible on the other.
598 #
599 # var x = new HashMap[String, Int]
600 # x["four"] = 4
601 # assert x.keys.has("four") == true
602 # assert x.keys.has("five") == false
603 fun keys: Collection[K] is abstract
604
605 # Is there no item in the collection?
606 #
607 # var x = new HashMap[String, Int]
608 # assert x.is_empty == true
609 # x["four"] = 4
610 # assert x.is_empty == false
611 fun is_empty: Bool is abstract
612
613 # Alias for `not is_empty`.
614 #
615 # Some people prefer to have conditions grammatically easier to read.
616 #
617 # var map = new HashMap[String, Int]
618 # assert map.not_empty == false
619 # map["one"] = 1
620 # assert map.not_empty == true
621 fun not_empty: Bool do return not self.is_empty
622
623 # Number of items in the collection.
624 #
625 # var x = new HashMap[String, Int]
626 # assert x.length == 0
627 # x["four"] = 4
628 # assert x.length == 1
629 # x["five"] = 5
630 # assert x.length == 2
631 fun length: Int is abstract
632
633 # Called by the underling implementation of `[]` to provide a default value when a `key` has no value
634 # By default the behavior is to abort.
635 #
636 # Note: the value is returned *as is*, implementations may want to store the value in the map before returning it
637 # @toimplement
638 protected fun provide_default_value(key: nullable Object): V do abort
639
640 # Does `self` and `other` have the same keys associated with the same values?
641 #
642 # ~~~
643 # var a = new HashMap[String, Int]
644 # var b = new ArrayMap[Object, Numeric]
645 # assert a == b
646 # a["one"] = 1
647 # assert a != b
648 # b["one"] = 1
649 # assert a == b
650 # b["one"] = 2
651 # assert a != b
652 # ~~~
653 redef fun ==(other)
654 do
655 if not other isa MapRead[nullable Object, nullable Object] then return false
656 if other.length != self.length then return false
657 for k, v in self do
658 if not other.has_key(k) then return false
659 if other[k] != v then return false
660 end
661 return true
662 end
663
664 # A hashcode based on the hashcode of the keys and the values.
665 #
666 # ~~~
667 # var a = new HashMap[String, Int]
668 # var b = new ArrayMap[Object, Numeric]
669 # a["one"] = 1
670 # b["one"] = 1
671 # assert a.hash == b.hash
672 # ~~~
673 redef fun hash
674 do
675 var res = length
676 for k, v in self do
677 if k != null then res += k.hash * 7
678 if v != null then res += v.hash * 11
679 end
680 return res
681 end
682 end
683
684 # Maps are associative collections: `key` -> `item`.
685 #
686 # The main operator over maps is [].
687 #
688 # var map: Map[String, Int] = new ArrayMap[String, Int]
689 # # ...
690 # map["one"] = 1 # Associate 'one' to '1'
691 # map["two"] = 2 # Associate 'two' to '2'
692 # assert map["one"] == 1
693 # assert map["two"] == 2
694 #
695 # Instances of maps can be used with the for structure
696 #
697 # for key, value in map do
698 # assert (key == "one" and value == 1) or (key == "two" and value == 2)
699 # end
700 #
701 # The keys and values in the map can also be manipulated directly with the `keys` and `values` methods.
702 #
703 # assert map.keys.has("one") == true
704 # assert map.keys.has("tree") == false
705 # assert map.values.has(1) == true
706 # assert map.values.has(3) == false
707 #
708 interface Map[K, V]
709 super MapRead[K, V]
710
711 # Set the `value` at `key`.
712 #
713 # Values can then get retrieved with `[]`.
714 #
715 # var x = new HashMap[String, Int]
716 # x["four"] = 4
717 # assert x["four"] == 4
718 #
719 # If the key was associated with a value, this old value is discarded
720 # and replaced with the new one.
721 #
722 # x["four"] = 40
723 # assert x["four"] == 40
724 # assert x.values.has(4) == false
725 #
726 fun []=(key: K, value: V) is abstract
727
728 # Add each (key,value) of `map` into `self`.
729 # If a same key exists in `map` and `self`, then the value in self is discarded.
730 #
731 # var x = new HashMap[String, Int]
732 # x["four"] = 4
733 # x["five"] = 5
734 # var y = new HashMap[String, Int]
735 # y["four"] = 40
736 # y["nine"] = 90
737 # x.add_all y
738 # assert x["four"] == 40
739 # assert x["five"] == 5
740 # assert x["nine"] == 90
741 fun add_all(map: MapRead[K, V])
742 do
743 var i = map.iterator
744 while i.is_ok do
745 self[i.key] = i.item
746 i.next
747 end
748 end
749
750 # Alias for `add_all`
751 fun recover_with(map: MapRead[K, V]) is deprecated do add_all(map)
752
753 # Remove all items
754 #
755 # var x = new HashMap[String, Int]
756 # x["four"] = 4
757 # x.clear
758 # assert x.keys.has("four") == false
759 #
760 # ENSURE `is_empty`
761 fun clear is abstract
762
763 redef fun values: RemovableCollection[V] is abstract
764
765 redef fun keys: RemovableCollection[K] is abstract
766 end
767
768 # Iterators for Map.
769 interface MapIterator[K, V]
770 # The current item.
771 # Require `is_ok`.
772 fun item: V is abstract
773
774 # The key of the current item.
775 # Require `is_ok`.
776 fun key: K is abstract
777
778 # Jump to the next item.
779 # Require `is_ok`.
780 fun next is abstract
781
782 # Is there a current item ?
783 fun is_ok: Bool is abstract
784
785 # Set a new `item` at `key`.
786 #fun item=(item: E) is abstract
787
788 # Pre-iteration hook.
789 #
790 # Used to inform `self` that the iteration is starting.
791 # Specific iterators can use this to prepare some resources.
792 #
793 # Is automatically invoked at the beginning of `for` structures.
794 #
795 # Do nothing by default.
796 fun start do end
797
798 # Post-iteration hook.
799 #
800 # Used to inform `self` that the iteration is over.
801 # Specific iterators can use this to free some resources.
802 #
803 # Is automatically invoked at the end of `for` structures.
804 #
805 # Do nothing by default.
806 fun finish do end
807 end
808
809 # Iterator on a 'keys' point of view of a map
810 class MapKeysIterator[K, V]
811 super Iterator[K]
812 # The original iterator
813 var original_iterator: MapIterator[K, V]
814
815 redef fun is_ok do return self.original_iterator.is_ok
816 redef fun next do self.original_iterator.next
817 redef fun item do return self.original_iterator.key
818 end
819
820 # Iterator on a 'values' point of view of a map
821 class MapValuesIterator[K, V]
822 super Iterator[V]
823 # The original iterator
824 var original_iterator: MapIterator[K, V]
825
826 redef fun is_ok do return self.original_iterator.is_ok
827 redef fun next do self.original_iterator.next
828 redef fun item do return self.original_iterator.item
829 end
830
831 # Sequences are indexed collections.
832 # The first item is 0. The last is `length-1`.
833 #
834 # The order is the main caracteristic of sequence
835 # and all concrete implementation of sequences are basically interchangeable.
836 interface SequenceRead[E]
837 super Collection[E]
838
839 # Get the first item.
840 # Is equivalent with `self[0]`.
841 #
842 # var a = [1,2,3]
843 # assert a.first == 1
844 #
845 # REQUIRE `not is_empty`
846 redef fun first
847 do
848 assert not_empty: not is_empty
849 return self[0]
850 end
851
852 # Return the index-th element of the sequence.
853 # The first element is 0 and the last is `length-1`
854 # If index is invalid, the program aborts
855 #
856 # var a = [10,20,30]
857 # assert a[0] == 10
858 # assert a[1] == 20
859 # assert a[2] == 30
860 #
861 # REQUIRE `index >= 0 and index < length`
862 fun [](index: Int): E is abstract
863
864 # Return the index-th element but wrap
865 #
866 # Whereas `self[]` requires the index to exists, the `modulo` accessor automatically
867 # wraps overbound and underbouds indexes.
868 #
869 # ~~~
870 # var a = [10,20,30]
871 # assert a.modulo(1) == 20
872 # assert a.modulo(3) == 10
873 # assert a.modulo(-1) == 30
874 # assert a.modulo(-10) == 30
875 # ~~~
876 #
877 # REQUIRE `not_empty`
878 # ENSURE `result == self[modulo_index(index)]`
879 fun modulo(index: Int): E do return self[modulo_index(index)]
880
881 # Returns the real index for a modulo index.
882 #
883 # ~~~
884 # var a = [10,20,30]
885 # assert a.modulo_index(1) == 1
886 # assert a.modulo_index(3) == 0
887 # assert a.modulo_index(-1) == 2
888 # assert a.modulo_index(-10) == 2
889 # ~~~
890 #
891 # REQUIRE `not_empty`
892 fun modulo_index(index: Int): Int
893 do
894 var length = self.length
895 if index >= 0 then
896 return index % length
897 else
898 return length - (-1 - index) % length - 1
899 end
900 end
901
902 # Try to get an element, return `null` if the `index` is invalid.
903 #
904 # ~~~
905 # var a = [10,20,30]
906 # assert a.get_or_null(1) == 20
907 # assert a.get_or_null(3) == null
908 # assert a.get_or_null(-1) == null
909 # assert a.get_or_null(-10) == null
910 # ~~~
911 fun get_or_null(index: Int): nullable E
912 do
913 if index >= 0 and index < length then return self[index]
914 return null
915 end
916
917 # Try to get an element, return `default` if the `index` is invalid.
918 #
919 # ~~~
920 # var a = [10,20,30]
921 # assert a.get_or_default(1, -1) == 20
922 # assert a.get_or_default(3, -1) == -1
923 # assert a.get_or_default(-1, -1) == -1
924 # assert a.get_or_default(-10, -1) == -1
925 # ~~~
926 fun get_or_default(index: Int, default: E): E
927 do
928 if index >= 0 and index < length then return self[index]
929 return default
930 end
931
932 # Get the last item.
933 # Is equivalent with `self[length-1]`.
934 #
935 # var a = [1,2,3]
936 # assert a.last == 3
937 #
938 # REQUIRE `not is_empty`
939 fun last: E
940 do
941 assert not_empty: not is_empty
942 return self[length-1]
943 end
944
945 # The index of the first occurrence of `item`.
946 # Return -1 if `item` is not found.
947 # Comparison is done with `==`.
948 #
949 # var a = [10,20,30,10,20,30]
950 # assert a.index_of(20) == 1
951 # assert a.index_of(40) == -1
952 fun index_of(item: nullable Object): Int do return index_of_from(item, 0)
953
954 # The index of the last occurrence of `item`.
955 # Return -1 if `item` is not found.
956 # Comparison is done with `==`.
957 #
958 # var a = [10,20,30,10,20,30]
959 # assert a.last_index_of(20) == 4
960 # assert a.last_index_of(40) == -1
961 fun last_index_of(item: nullable Object): Int do return last_index_of_from(item, length-1)
962
963 # The index of the first occurrence of `item`, starting from pos.
964 # Return -1 if `item` is not found.
965 # Comparison is done with `==`.
966 #
967 # var a = [10,20,30,10,20,30]
968 # assert a.index_of_from(20, 3) == 4
969 # assert a.index_of_from(20, 4) == 4
970 # assert a.index_of_from(20, 5) == -1
971 fun index_of_from(item: nullable Object, pos: Int): Int
972 do
973 var p = 0
974 var i = iterator
975 while i.is_ok do
976 if p>=pos and i.item == item then return i.index
977 i.next
978 p += 1
979 end
980 return -1
981 end
982
983 # The index of the last occurrence of `item` starting from `pos` and decrementing.
984 # Return -1 if `item` is not found.
985 # Comparison is done with `==`.
986 #
987 # var a = [10,20,30,10,20,30]
988 # assert a.last_index_of_from(20, 2) == 1
989 # assert a.last_index_of_from(20, 1) == 1
990 # assert a.last_index_of_from(20, 0) == -1
991 fun last_index_of_from(item: nullable Object, pos: Int): Int do
992 var i = pos
993 while i >= 0 do
994 if self[i] == item then return i
995 i -= 1
996 end
997 return -1
998 end
999
1000 # Two sequences are equals if they have the same items in the same order.
1001 #
1002 # var a = new List[Int]
1003 # a.add(1)
1004 # a.add(2)
1005 # a.add(3)
1006 # assert a == [1,2,3]
1007 # assert a != [1,3,2]
1008 redef fun ==(o)
1009 do
1010 if not o isa SequenceRead[nullable Object] then return false
1011 var l = length
1012 if o.length != l then return false
1013 var i = 0
1014 while i < l do
1015 if self[i] != o[i] then return false
1016 i += 1
1017 end
1018 return true
1019 end
1020
1021 # Because of the law between `==` and `hash`, `hash` is redefined to be the sum of the hash of the elements
1022 redef fun hash
1023 do
1024 # The 17 and 2/3 magic numbers were determined empirically.
1025 # Note: the standard hash functions djb2, sbdm and fnv1 were also
1026 # tested but were comparable (or worse).
1027 var res = 17 + length
1028 for e in self do
1029 res = res * 3 / 2
1030 if e != null then res += e.hash
1031 end
1032 return res
1033 end
1034
1035 redef fun iterator: IndexedIterator[E] is abstract
1036
1037 # Gets a new Iterator starting at position `pos`
1038 #
1039 # var iter = [10,20,30,40,50].iterator_from(2)
1040 # assert iter.to_a == [30, 40, 50]
1041 fun iterator_from(pos: Int): IndexedIterator[E]
1042 do
1043 var res = iterator
1044 while pos > 0 and res.is_ok do
1045 res.next
1046 pos -= 1
1047 end
1048 return res
1049 end
1050
1051 # Gets an iterator starting at the end and going backwards
1052 #
1053 # var reviter = [1,2,3].reverse_iterator
1054 # assert reviter.to_a == [3,2,1]
1055 fun reverse_iterator: IndexedIterator[E] is abstract
1056
1057 # Gets an iterator on the chars of self starting from `pos`
1058 #
1059 # var reviter = [10,20,30,40,50].reverse_iterator_from(2)
1060 # assert reviter.to_a == [30,20,10]
1061 fun reverse_iterator_from(pos: Int): IndexedIterator[E]
1062 do
1063 var res = reverse_iterator
1064 while pos > 0 and res.is_ok do
1065 res.next
1066 pos -= 1
1067 end
1068 return res
1069 end
1070 end
1071
1072 # Sequence are indexed collection.
1073 # The first item is 0. The last is `length-1`.
1074 interface Sequence[E]
1075 super SequenceRead[E]
1076 super SimpleCollection[E]
1077
1078 # Set the first item.
1079 # Is equivalent with `self[0] = item`.
1080 #
1081 # var a = [1,2,3]
1082 # a.first = 10
1083 # assert a == [10,2,3]
1084 fun first=(item: E)
1085 do self[0] = item end
1086
1087 # Set the last item.
1088 # Is equivalent with `self[length-1] = item`.
1089 #
1090 # var a = [1,2,3]
1091 # a.last = 10
1092 # assert a == [1,2,10]
1093 #
1094 # If the sequence is empty, `last=` is equivalent with `self[0]=` (thus with `first=`)
1095 #
1096 # var b = new Array[Int]
1097 # b.last = 10
1098 # assert b == [10]
1099 fun last=(item: E)
1100 do
1101 var l = length
1102 if l > 0 then
1103 self[l-1] = item
1104 else
1105 self[0] = item
1106 end
1107 end
1108
1109 # A synonym of `push`
1110 redef fun add(e) do push(e)
1111
1112 # Add an item after the last one.
1113 #
1114 # var a = [1,2,3]
1115 # a.push(10)
1116 # a.push(20)
1117 # assert a == [1,2,3,10,20]
1118 fun push(e: E) is abstract
1119
1120 # Add each item of `coll` after the last.
1121 #
1122 # var a = [1,2,3]
1123 # a.append([7..9])
1124 # assert a == [1,2,3,7,8,9]
1125 #
1126 # Alias of `add_all`
1127 fun append(coll: Collection[E]) do add_all(coll)
1128
1129 # Remove the last item.
1130 #
1131 # var a = [1,2,3]
1132 # assert a.pop == 3
1133 # assert a.pop == 2
1134 # assert a == [1]
1135 #
1136 # REQUIRE `not is_empty`
1137 fun pop: E is abstract
1138
1139 # Add an item before the first one.
1140 #
1141 # var a = [1,2,3]
1142 # a.unshift(10)
1143 # a.unshift(20)
1144 # assert a == [20,10,1,2,3]
1145 fun unshift(e: E) is abstract
1146
1147 # Add all items of `coll` before the first one.
1148 #
1149 # var a = [1,2,3]
1150 # a.prepend([7..9])
1151 # assert a == [7,8,9,1,2,3]
1152 #
1153 # Alias of `insert_at(coll, 0)`
1154 fun prepend(coll: Collection[E]) do insert_all(coll, 0)
1155
1156 # Remove the first item.
1157 # The second item thus become the first.
1158 #
1159 # var a = [1,2,3]
1160 # assert a.shift == 1
1161 # assert a.shift == 2
1162 # assert a == [3]
1163 #
1164 # REQUIRE `not is_empty`
1165 fun shift: E is abstract
1166
1167 # Set the `item` at `index`.
1168 #
1169 # var a = [10,20,30]
1170 # a[1] = 200
1171 # assert a == [10,200,30]
1172 #
1173 # like with `[]`, index should be between `0` and `length-1`
1174 # However, if `index==length`, `[]=` works like `push`.
1175 #
1176 # a[3] = 400
1177 # assert a == [10,200,30,400]
1178 #
1179 # REQUIRE `index >= 0 and index <= length`
1180 fun []=(index: Int, item: E) is abstract
1181
1182 # Set the index-th element but wrap
1183 #
1184 # Whereas `self[]=` requires the index to exists, the `modulo` accessor automatically
1185 # wraps overbound and underbouds indexes.
1186 #
1187 # ~~~
1188 # var a = [10,20,30]
1189 # a.modulo(1) = 200
1190 # a.modulo(3) = 100
1191 # a.modulo(-1) = 300
1192 # a.modulo(-10) = 301
1193 # assert a == [100, 200, 301]
1194 # ~~~
1195 #
1196 # REQUIRE `not_empty`
1197 # ENSURE `self[modulo_index(index)] == value`
1198 fun modulo=(index: Int, value: E) do self[modulo_index(index)] = value
1199
1200 # Insert an element at a given position, following elements are shifted.
1201 #
1202 # var a = [10, 20, 30, 40]
1203 # a.insert(100, 2)
1204 # assert a == [10, 20, 100, 30, 40]
1205 #
1206 # REQUIRE `index >= 0 and index <= length`
1207 # ENSURE `self[index] == item`
1208 fun insert(item: E, index: Int) is abstract
1209
1210 # Insert all elements at a given position, following elements are shifted.
1211 #
1212 # var a = [10, 20, 30, 40]
1213 # a.insert_all([100..102], 2)
1214 # assert a == [10, 20, 100, 101, 102, 30, 40]
1215 #
1216 # REQUIRE `index >= 0 and index <= length`
1217 # ENSURE `self[index] == coll.first`
1218 fun insert_all(coll: Collection[E], index: Int)
1219 do
1220 assert index >= 0 and index < length
1221 if index == length then
1222 add_all(coll)
1223 end
1224 for c in coll do
1225 insert(c, index)
1226 index += 1
1227 end
1228 end
1229
1230 # Remove the item at `index` and shift all following elements
1231 #
1232 # var a = [10,20,30]
1233 # a.remove_at(1)
1234 # assert a == [10,30]
1235 #
1236 # REQUIRE `index >= 0 and index < length`
1237 fun remove_at(index: Int) is abstract
1238
1239 # Rotates the elements of self once to the left
1240 #
1241 # ~~~nit
1242 # var a = [12, 23, 34, 45]
1243 # a.rotate_left
1244 # assert a == [23, 34, 45, 12]
1245 # ~~~
1246 fun rotate_left do
1247 var fst = shift
1248 push fst
1249 end
1250
1251 # Rotates the elements of self once to the right
1252 #
1253 # ~~~nit
1254 # var a = [12, 23, 34, 45]
1255 # a.rotate_right
1256 # assert a == [45, 12, 23, 34]
1257 # ~~~
1258 fun rotate_right do
1259 var lst = pop
1260 unshift lst
1261 end
1262 end
1263
1264 # Iterators on indexed collections.
1265 interface IndexedIterator[E]
1266 super Iterator[E]
1267 # The index of the current item.
1268 fun index: Int is abstract
1269 end
1270
1271 # Associative arrays that internally uses couples to represent each (key, value) pairs.
1272 # This is an helper class that some specific implementation of Map may implements.
1273 interface CoupleMap[K, V]
1274 super Map[K, V]
1275
1276 # Return the couple of the corresponding key
1277 # Return null if the key is no associated element
1278 protected fun couple_at(key: nullable Object): nullable Couple[K, V] is abstract
1279
1280 # Return a new iteralot on all couples
1281 # Used to provide `iterator` and others
1282 protected fun couple_iterator: Iterator[Couple[K,V]] is abstract
1283
1284 redef fun iterator do return new CoupleMapIterator[K,V](couple_iterator)
1285
1286 redef fun [](key)
1287 do
1288 var c = couple_at(key)
1289 if c == null then
1290 return provide_default_value(key)
1291 else
1292 return c.second
1293 end
1294 end
1295
1296 redef fun has_key(key) do return couple_at(key) != null
1297 end
1298
1299 # Iterator on CoupleMap
1300 #
1301 # Actually it is a wrapper around an iterator of the internal array of the map.
1302 private class CoupleMapIterator[K, V]
1303 super MapIterator[K, V]
1304 redef fun item do return _iter.item.second
1305
1306 #redef fun item=(e) do _iter.item.second = e
1307
1308 redef fun key do return _iter.item.first
1309
1310 redef fun is_ok do return _iter.is_ok
1311
1312 redef fun next
1313 do
1314 _iter.next
1315 end
1316
1317 var iter: Iterator[Couple[K,V]]
1318 end
1319
1320 # Some tools ###################################################################
1321
1322 # Two objects in a simple structure.
1323 class Couple[F, S]
1324
1325 # The first element of the couple.
1326 var first: F is writable
1327
1328 # The second element of the couple.
1329 var second: S is writable
1330 end