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