lib: promote implementations in NaiveCollection to Collection
[nit.git] / lib / standard / 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 # This module define several abstract collection classes.
14 module abstract_collection
15
16 import kernel
17
18 # The root of the collection hierarchy.
19 #
20 # Instances of this class offers an iterator method.
21 #
22 # Collections instances can use the "for" structure:
23 # var x: Collection[U]
24 # # ...
25 # for u in x do
26 # # u is a U
27 # # ...
28 # end
29 # that is equivalent with
30 # var x: Collection[U]
31 # # ...
32 # var i = x.iterator
33 # while i.is_ok do
34 # var u = i.item # u is a U
35 # # ...
36 # i.next
37 # end
38 #
39 # This abstract class implements its others methods with an iterator.
40 # Subclasses may redefine them with an efficient implementation.
41 interface Collection[E]
42 # Get a new iterator on the collection.
43 fun iterator: Iterator[E] is abstract
44
45 # Iterate over each element of the collection
46 fun iterate
47 !each(e: E)
48 do
49 var i = iterator
50 while i.is_ok do
51 each(i.item)
52 i.next
53 end
54 end
55
56 # Is there no item in the collection?
57 #
58 # assert [1,2,3].is_empty == false
59 # assert [1..1[.is_empty == true
60 fun is_empty: Bool do return length == 0
61
62 # Number of items in the collection.
63 #
64 # assert [10,20,30].length == 3
65 # assert [20..30[.length == 10
66 fun length: Int
67 do
68 var nb = 0
69 for i in self do nb += 1
70 return nb
71 end
72
73
74 # Is `item` in the collection ?
75 # Comparisons are done with ==
76 #
77 # assert [1,2,3].has(2) == true
78 # assert [1,2,3].has(9) == false
79 # assert [1..5[.has(2) == true
80 # assert [1..5[.has(9) == false
81 fun has(item: E): Bool
82 do
83 for i in self do if i == item then return true
84 return false
85 end
86
87 # Is the collection contain only `item`?
88 # Comparisons are done with ==
89 # Return true if the collection is empty.
90 #
91 # assert [1,1,1].has_only(1) == true
92 # assert [1,2,3].has_only(1) == false
93 # assert [1..1].has_only(1) == true
94 # assert [1..3].has_only(1) == false
95 # assert [3..3[.has_only(1) == true # empty collection
96 #
97 # ENSURE `is_empty implies result == true`
98 fun has_only(item: E): Bool
99 do
100 for i in self do if i != item then return false
101 return true
102 end
103
104 # How many occurrences of `item` are in the collection?
105 # Comparisons are done with ==
106 #
107 # assert [10,20,10].count(10) == 2
108 fun count(item: E): Int
109 do
110 var nb = 0
111 for i in self do if i == item then nb += 1
112 return nb
113 end
114
115 # Return one the item of the collection
116 #
117 # assert [1,2,3].first == 1
118 fun first: E
119 do
120 assert length > 0
121 return iterator.item
122 end
123
124 # Is the collection contains all the elements of `other`?
125 #
126 # assert [1,1,1].has_all([1]) == true
127 # assert [1,1,1].has_all([1,2]) == false
128 # assert [1,3,4,2].has_all([1..2]) == true
129 # assert [1,3,4,2].has_all([1..5]) == false
130 fun has_all(other: Collection[E]): Bool
131 do
132 for x in other do if not has(x) then return false
133 return true
134 end
135 end
136
137 # Naive implementation of collections method
138 # You only have to define iterator!
139 interface NaiveCollection[E]
140 super Collection[E]
141 end
142
143 # Instances of the Iterator class generates a series of elements, one at a time.
144 # They are mainly used with collections.
145 interface Iterator[E]
146 # The current item.
147 # Require `is_ok`.
148 fun item: E is abstract
149
150 # Jump to the next item.
151 # Require `is_ok`.
152 fun next is abstract
153
154 # Is there a current item ?
155 fun is_ok: Bool is abstract
156 end
157
158 # A collection that contains only one item.
159 class Container[E]
160 super Collection[E]
161
162 redef fun first do return _item
163
164 redef fun is_empty do return false
165
166 redef fun length do return 1
167
168 redef fun has(an_item) do return _item == an_item
169
170 redef fun has_only(an_item) do return _item == an_item
171
172 redef fun count(an_item)
173 do
174 if _item == an_item then
175 return 1
176 else
177 return 0
178 end
179 end
180
181 redef fun iterator do return new ContainerIterator[E](self)
182
183 # Create a new instance with a given initial value.
184 init(e: E) do _item = e
185
186 # The stored item
187 readable writable var _item: E
188 end
189
190 # This iterator is quite stupid since it is used for only one item.
191 class ContainerIterator[E]
192 super Iterator[E]
193 redef fun item do return _container.item
194
195 redef fun next do _is_ok = false
196
197 init(c: Container[E]) do _container = c
198
199 redef readable var _is_ok: Bool = true
200
201 var _container: Container[E]
202 end
203
204 # Items can be removed from this collection
205 interface RemovableCollection[E]
206 super Collection[E]
207 # Remove all items
208 fun clear is abstract
209
210 # Remove an occucence of `item`
211 fun remove(item: E) is abstract
212
213 # Remove all occurences of `item`
214 fun remove_all(item: E) do while has(item) do remove(item)
215 end
216
217 # Items can be added to these collections.
218 interface SimpleCollection[E]
219 super RemovableCollection[E]
220 # Add an item in a collection.
221 # Ensure col.has(item)
222 fun add(item: E) is abstract
223
224 # Add each item of `coll`.
225 fun add_all(coll: Collection[E]) do for i in coll do add(i)
226 end
227
228 # Abstract sets.
229 #
230 # Set contains contains only one element with the same value (according to ==).
231 # var s: Set[String] = new ArraySet[String]
232 # var a = "Hello"
233 # var b = "Hel" + "lo"
234 # # ...
235 # s.add(a)
236 # assert s.has(b) == true
237 interface Set[E: Object]
238 super SimpleCollection[E]
239
240 redef fun has_only(item)
241 do
242 var l = length
243 if l == 1 then
244 return has(item)
245 else if l == 0 then
246 return true
247 else
248 return false
249 end
250 end
251
252 # Only 0 or 1
253 redef fun count(item)
254 do
255 if has(item) then
256 return 1
257 else
258 return 0
259 end
260 end
261
262 # Synonym of remove since there is only one item
263 redef fun remove_all(item) do remove(item)
264
265 # Equality is defined on set and means that each set contains the same elements
266 redef fun ==(other)
267 do
268 if not other isa Set[Object] then return false
269 if other.length != length then return false
270 return has_all(other)
271 end
272 end
273
274 # MapRead are abstract associative collections: `key` -> `item`.
275 interface MapRead[K: Object, E]
276 # Get the item at `key`.
277 fun [](key: K): E is abstract
278
279 # Get the item at `key` or return `default` if not in map
280 fun get_or_default(key: K, default: E): E
281 do
282 if has_key(key) then return self[key]
283 return default
284 end
285
286 # Depreciated alias for `keys.has`
287 fun has_key(key: K): Bool do return self.keys.has(key)
288
289 # Get a new iterator on the map.
290 fun iterator: MapIterator[K, E] is abstract
291
292 # Iterate over each element of the collection
293 fun iterate
294 !each(k: K, v: E)
295 do
296 var i = iterator
297 while i.is_ok do
298 each(i.key, i.item)
299 i.next
300 end
301 end
302
303 # Return the point of view of self on the values only.
304 # Note that `self` and `values` are views on the same data;
305 # therefore any modification of one is visible on the other.
306 fun values: Collection[E] is abstract
307
308 # Return the point of view of self on the keys only.
309 # Note that `self` and `keys` are views on the same data;
310 # therefore any modification of one is visible on the other.
311 fun keys: Collection[K] is abstract
312
313 # Is there no item in the collection?
314 fun is_empty: Bool is abstract
315
316 # Number of items in the collection.
317 fun length: Int is abstract
318 end
319
320 # Maps are associative collections: `key` -> `item`.
321 #
322 # The main operator over maps is [].
323 #
324 # var map: Map[String, Int] = new ArrayMap[String, Int]
325 # # ...
326 # map["one"] = 1 # Associate 'one' to '1'
327 # map["two"] = 2 # Associate 'two' to '2'
328 # assert map["one"] == 1
329 # assert map["two"] == 2
330 #
331 # Instances of maps can be used with the for structure
332 #
333 # for key, value in map do
334 # assert (key == "one" and value == 1) or (key == "two" and value == 2)
335 # end
336 #
337 # The keys and values in the map can also be manipulated directly with the `keys` and `values` methods.
338 #
339 # assert map.keys.has("one") == true
340 # assert map.keys.has("tree") == false
341 # assert map.values.has(1) == true
342 # assert map.values.has(3) == false
343 #
344 interface Map[K: Object, E]
345 super MapRead[K, E]
346 # Set the`item` at `key`.
347 fun []=(key: K, item: E) is abstract
348
349 # Add each (key,value) of `map` into `self`.
350 # If a same key exists in `map` and `self`, then the value in self is discarded.
351 fun recover_with(map: Map[K, E])
352 do
353 var i = map.iterator
354 while i.is_ok do
355 self[i.key] = i.item
356 i.next
357 end
358 end
359
360 # Remove all items
361 fun clear is abstract
362
363 redef fun values: RemovableCollection[E] is abstract
364
365 redef fun keys: RemovableCollection[K] is abstract
366 end
367
368 # Iterators for Map.
369 interface MapIterator[K: Object, E]
370 # The current item.
371 # Require `is_ok`.
372 fun item: E is abstract
373
374 # The key of the current item.
375 # Require `is_ok`.
376 fun key: K is abstract
377
378 # Jump to the next item.
379 # Require `is_ok`.
380 fun next is abstract
381
382 # Is there a current item ?
383 fun is_ok: Bool is abstract
384
385 # Set a new `item` at `key`.
386 #fun item=(item: E) is abstract
387 end
388
389 # Iterator on a 'keys' point of view of a map
390 class MapKeysIterator[K: Object, V]
391 super Iterator[K]
392 # The original iterator
393 var iterator: MapIterator[K, V]
394
395 redef fun is_ok do return self.iterator.is_ok
396 redef fun next do self.iterator.next
397 redef fun item do return self.iterator.key
398 end
399
400 # Iterator on a 'values' point of view of a map
401 class MapValuesIterator[K: Object, V]
402 super Iterator[V]
403 # The original iterator
404 var iterator: MapIterator[K, V]
405
406 redef fun is_ok do return self.iterator.is_ok
407 redef fun next do self.iterator.next
408 redef fun item do return self.iterator.item
409 end
410
411 # Sequences are indexed collections.
412 # The first item is 0. The last is `length-1`.
413 interface SequenceRead[E]
414 super Collection[E]
415 # Get the first item.
416 # Is equivalent with `self[0]`.
417 redef fun first
418 do
419 assert not_empty: not is_empty
420 return self[0]
421 end
422
423 # Return the index=th element of the sequence.
424 # The first element is 0 and the last if `length-1`
425 # If index is invalid, the program aborts
426 fun [](index: Int): E is abstract
427
428 # Get the last item.
429 # Is equivalent with `self[length-1]`.
430 fun last: E
431 do
432 assert not_empty: not is_empty
433 return self[length-1]
434 end
435
436 # Return the index of the first occurrence of `item`.
437 # Return -1 if `item` is not found
438 # Comparison is done with ==
439 fun index_of(item: E): Int
440 do
441 var i = iterator
442 while i.is_ok do
443 if i.item == item then return i.index
444 i.next
445 end
446 return -1
447 end
448
449 redef fun iterator: IndexedIterator[E] is abstract
450 end
451
452 # Sequence are indexed collection.
453 # The first item is 0. The last is `length-1`.
454 interface Sequence[E]
455 super SequenceRead[E]
456 super SimpleCollection[E]
457
458 # Set the first item.
459 # Is equivalent with `self[0] = item`.
460 fun first=(item: E)
461 do self[0] = item end
462
463 # Set the last item.
464 # Is equivalent with `self[length-1] = item`.
465 fun last=(item: E)
466 do
467 var l = length
468 if l > 0 then
469 self[l-1] = item
470 else
471 self[0] = item
472 end
473 end
474
475 # A synonym of `push`
476 redef fun add(e) do push(e)
477
478 # Add an item after the last.
479 fun push(e: E) is abstract
480
481 # Add each item of `coll` after the last.
482 fun append(coll: Collection[E]) do for i in coll do push(i)
483
484 # Remove the last item.
485 fun pop: E is abstract
486
487 # Add an item before the last.
488 fun unshift(e: E) is abstract
489
490 # Remove the first item.
491 # The second item become the first.
492 fun shift: E is abstract
493
494 # Set the `item` at `index`.
495 fun []=(index: Int, item: E) is abstract
496
497 # Remove the item at `index` and shift all following elements
498 fun remove_at(index: Int) is abstract
499 end
500
501 # Iterators on indexed collections.
502 interface IndexedIterator[E]
503 super Iterator[E]
504 # The index of the current item.
505 fun index: Int is abstract
506 end
507
508 # Associative arrays that internally uses couples to represent each (key, value) pairs.
509 interface CoupleMap[K: Object, E]
510 super Map[K, E]
511 # Return the couple of the corresponding key
512 # Return null if the key is no associated element
513 protected fun couple_at(key: K): nullable Couple[K, E] is abstract
514
515 redef fun [](key)
516 do
517 var c = couple_at(key)
518 if c == null then
519 abort
520 else
521 return c.second
522 end
523 end
524 end
525
526 # Iterator on CoupleMap
527 #
528 # Actually is is a wrapper around an iterator of the internal array of the map.
529 class CoupleMapIterator[K: Object, E]
530 super MapIterator[K, E]
531 redef fun item do return _iter.item.second
532
533 #redef fun item=(e) do _iter.item.second = e
534
535 redef fun key do return _iter.item.first
536
537 redef fun is_ok do return _iter.is_ok
538
539 redef fun next
540 do
541 _iter.next
542 end
543
544 var _iter: Iterator[Couple[K,E]]
545
546 init(i: Iterator[Couple[K,E]]) do _iter = i
547 end
548
549 # Some tools ###################################################################
550
551 # Two objects in a simple structure.
552 class Couple[F, S]
553
554 # The first element of the couple.
555 readable writable var _first: F
556
557 # The second element of the couple.
558 readable writable var _second: S
559
560 # Create a new instance with a first and a second object.
561 init(f: F, s: S)
562 do
563 _first = f
564 _second = s
565 end
566 end