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