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