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