lib/core: Make all `Set` cloneable
[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 # Get the last item.
816 # Is equivalent with `self[length-1]`.
817 #
818 # var a = [1,2,3]
819 # assert a.last == 3
820 #
821 # REQUIRE `not is_empty`
822 fun last: E
823 do
824 assert not_empty: not is_empty
825 return self[length-1]
826 end
827
828 # The index of the first occurrence of `item`.
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(20) == 1
834 # assert a.index_of(40) == -1
835 fun index_of(item: nullable Object): Int do return index_of_from(item, 0)
836
837 # The index of the last occurrence of `item`.
838 # Return -1 if `item` is not found.
839 # Comparison is done with `==`.
840 #
841 # var a = [10,20,30,10,20,30]
842 # assert a.last_index_of(20) == 4
843 # assert a.last_index_of(40) == -1
844 fun last_index_of(item: nullable Object): Int do return last_index_of_from(item, length-1)
845
846 # The index of the first occurrence of `item`, starting from pos.
847 # Return -1 if `item` is not found.
848 # Comparison is done with `==`.
849 #
850 # var a = [10,20,30,10,20,30]
851 # assert a.index_of_from(20, 3) == 4
852 # assert a.index_of_from(20, 4) == 4
853 # assert a.index_of_from(20, 5) == -1
854 fun index_of_from(item: nullable Object, pos: Int): Int
855 do
856 var p = 0
857 var i = iterator
858 while i.is_ok do
859 if p>=pos and i.item == item then return i.index
860 i.next
861 p += 1
862 end
863 return -1
864 end
865
866 # The index of the last occurrence of `item` starting from `pos` and decrementing.
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.last_index_of_from(20, 2) == 1
872 # assert a.last_index_of_from(20, 1) == 1
873 # assert a.last_index_of_from(20, 0) == -1
874 fun last_index_of_from(item: nullable Object, pos: Int): Int do
875 var i = pos
876 while i >= 0 do
877 if self[i] == item then return i
878 i -= 1
879 end
880 return -1
881 end
882
883 # Two sequences are equals if they have the same items in the same order.
884 #
885 # var a = new List[Int]
886 # a.add(1)
887 # a.add(2)
888 # a.add(3)
889 # assert a == [1,2,3]
890 # assert a != [1,3,2]
891 redef fun ==(o)
892 do
893 if not o isa SequenceRead[nullable Object] then return false
894 var l = length
895 if o.length != l then return false
896 var i = 0
897 while i < l do
898 if self[i] != o[i] then return false
899 i += 1
900 end
901 return true
902 end
903
904 # Because of the law between `==` and `hash`, `hash` is redefined to be the sum of the hash of the elements
905 redef fun hash
906 do
907 # The 17 and 2/3 magic numbers were determined empirically.
908 # Note: the standard hash functions djb2, sbdm and fnv1 were also
909 # tested but were comparable (or worse).
910 var res = 17 + length
911 for e in self do
912 res = res * 3 / 2
913 if e != null then res += e.hash
914 end
915 return res
916 end
917
918 redef fun iterator: IndexedIterator[E] is abstract
919
920 # Gets a new Iterator starting at position `pos`
921 #
922 # var iter = [10,20,30,40,50].iterator_from(2)
923 # assert iter.to_a == [30, 40, 50]
924 fun iterator_from(pos: Int): IndexedIterator[E]
925 do
926 var res = iterator
927 while pos > 0 and res.is_ok do
928 res.next
929 pos -= 1
930 end
931 return res
932 end
933
934 # Gets an iterator starting at the end and going backwards
935 #
936 # var reviter = [1,2,3].reverse_iterator
937 # assert reviter.to_a == [3,2,1]
938 fun reverse_iterator: IndexedIterator[E] is abstract
939
940 # Gets an iterator on the chars of self starting from `pos`
941 #
942 # var reviter = [10,20,30,40,50].reverse_iterator_from(2)
943 # assert reviter.to_a == [30,20,10]
944 fun reverse_iterator_from(pos: Int): IndexedIterator[E]
945 do
946 var res = reverse_iterator
947 while pos > 0 and res.is_ok do
948 res.next
949 pos -= 1
950 end
951 return res
952 end
953 end
954
955 # Sequence are indexed collection.
956 # The first item is 0. The last is `length-1`.
957 interface Sequence[E]
958 super SequenceRead[E]
959 super SimpleCollection[E]
960
961 # Set the first item.
962 # Is equivalent with `self[0] = item`.
963 #
964 # var a = [1,2,3]
965 # a.first = 10
966 # assert a == [10,2,3]
967 fun first=(item: E)
968 do self[0] = item end
969
970 # Set the last item.
971 # Is equivalent with `self[length-1] = item`.
972 #
973 # var a = [1,2,3]
974 # a.last = 10
975 # assert a == [1,2,10]
976 #
977 # If the sequence is empty, `last=` is equivalent with `self[0]=` (thus with `first=`)
978 #
979 # var b = new Array[Int]
980 # b.last = 10
981 # assert b == [10]
982 fun last=(item: E)
983 do
984 var l = length
985 if l > 0 then
986 self[l-1] = item
987 else
988 self[0] = item
989 end
990 end
991
992 # A synonym of `push`
993 redef fun add(e) do push(e)
994
995 # Add an item after the last one.
996 #
997 # var a = [1,2,3]
998 # a.push(10)
999 # a.push(20)
1000 # assert a == [1,2,3,10,20]
1001 fun push(e: E) is abstract
1002
1003 # Add each item of `coll` after the last.
1004 #
1005 # var a = [1,2,3]
1006 # a.append([7..9])
1007 # assert a == [1,2,3,7,8,9]
1008 #
1009 # Alias of `add_all`
1010 fun append(coll: Collection[E]) do add_all(coll)
1011
1012 # Remove the last item.
1013 #
1014 # var a = [1,2,3]
1015 # assert a.pop == 3
1016 # assert a.pop == 2
1017 # assert a == [1]
1018 #
1019 # REQUIRE `not is_empty`
1020 fun pop: E is abstract
1021
1022 # Add an item before the first one.
1023 #
1024 # var a = [1,2,3]
1025 # a.unshift(10)
1026 # a.unshift(20)
1027 # assert a == [20,10,1,2,3]
1028 fun unshift(e: E) is abstract
1029
1030 # Add all items of `coll` before the first one.
1031 #
1032 # var a = [1,2,3]
1033 # a.prepend([7..9])
1034 # assert a == [7,8,9,1,2,3]
1035 #
1036 # Alias of `insert_at(coll, 0)`
1037 fun prepend(coll: Collection[E]) do insert_all(coll, 0)
1038
1039 # Remove the first item.
1040 # The second item thus become the first.
1041 #
1042 # var a = [1,2,3]
1043 # assert a.shift == 1
1044 # assert a.shift == 2
1045 # assert a == [3]
1046 #
1047 # REQUIRE `not is_empty`
1048 fun shift: E is abstract
1049
1050 # Set the `item` at `index`.
1051 #
1052 # var a = [10,20,30]
1053 # a[1] = 200
1054 # assert a == [10,200,30]
1055 #
1056 # like with `[]`, index should be between `0` and `length-1`
1057 # However, if `index==length`, `[]=` works like `push`.
1058 #
1059 # a[3] = 400
1060 # assert a == [10,200,30,400]
1061 #
1062 # REQUIRE `index >= 0 and index <= length`
1063 fun []=(index: Int, item: E) is abstract
1064
1065 # Insert an element at a given position, following elements are shifted.
1066 #
1067 # var a = [10, 20, 30, 40]
1068 # a.insert(100, 2)
1069 # assert a == [10, 20, 100, 30, 40]
1070 #
1071 # REQUIRE `index >= 0 and index <= length`
1072 # ENSURE `self[index] == item`
1073 fun insert(item: E, index: Int) is abstract
1074
1075 # Insert all elements at a given position, following elements are shifted.
1076 #
1077 # var a = [10, 20, 30, 40]
1078 # a.insert_all([100..102], 2)
1079 # assert a == [10, 20, 100, 101, 102, 30, 40]
1080 #
1081 # REQUIRE `index >= 0 and index <= length`
1082 # ENSURE `self[index] == coll.first`
1083 fun insert_all(coll: Collection[E], index: Int)
1084 do
1085 assert index >= 0 and index < length
1086 if index == length then
1087 add_all(coll)
1088 end
1089 for c in coll do
1090 insert(c, index)
1091 index += 1
1092 end
1093 end
1094
1095 # Remove the item at `index` and shift all following elements
1096 #
1097 # var a = [10,20,30]
1098 # a.remove_at(1)
1099 # assert a == [10,30]
1100 #
1101 # REQUIRE `index >= 0 and index < length`
1102 fun remove_at(index: Int) is abstract
1103 end
1104
1105 # Iterators on indexed collections.
1106 interface IndexedIterator[E]
1107 super Iterator[E]
1108 # The index of the current item.
1109 fun index: Int is abstract
1110 end
1111
1112 # Associative arrays that internally uses couples to represent each (key, value) pairs.
1113 # This is an helper class that some specific implementation of Map may implements.
1114 interface CoupleMap[K, V]
1115 super Map[K, V]
1116
1117 # Return the couple of the corresponding key
1118 # Return null if the key is no associated element
1119 protected fun couple_at(key: nullable Object): nullable Couple[K, V] is abstract
1120
1121 # Return a new iteralot on all couples
1122 # Used to provide `iterator` and others
1123 protected fun couple_iterator: Iterator[Couple[K,V]] is abstract
1124
1125 redef fun iterator do return new CoupleMapIterator[K,V](couple_iterator)
1126
1127 redef fun [](key)
1128 do
1129 var c = couple_at(key)
1130 if c == null then
1131 return provide_default_value(key)
1132 else
1133 return c.second
1134 end
1135 end
1136
1137 redef fun has_key(key) do return couple_at(key) != null
1138 end
1139
1140 # Iterator on CoupleMap
1141 #
1142 # Actually it is a wrapper around an iterator of the internal array of the map.
1143 private class CoupleMapIterator[K, V]
1144 super MapIterator[K, V]
1145 redef fun item do return _iter.item.second
1146
1147 #redef fun item=(e) do _iter.item.second = e
1148
1149 redef fun key do return _iter.item.first
1150
1151 redef fun is_ok do return _iter.is_ok
1152
1153 redef fun next
1154 do
1155 _iter.next
1156 end
1157
1158 var iter: Iterator[Couple[K,V]]
1159 end
1160
1161 # Some tools ###################################################################
1162
1163 # Two objects in a simple structure.
1164 class Couple[F, S]
1165
1166 # The first element of the couple.
1167 var first: F is writable
1168
1169 # The second element of the couple.
1170 var second: S is writable
1171 end