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