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