metamodel: rename 'universal' to 'enum'
[nit.git] / lib / standard / collection / range.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 # Module for range of discrete objects.
14 package range
15
16 import abstract_collection
17
18 # Range of discrete objects.
19 class Range[E: Discrete]
20 super Collection[E]
21
22 redef readable var _first: E
23
24 # Get the last element.
25 readable var _last: E
26
27 # Get the element after the last one.
28 readable var _after: E
29
30 redef fun has(item) do return item >= _first and item <= _last
31
32 redef fun has_only(item) do return _first == item and item == _last
33
34 redef fun count(item)
35 do
36 if has(item) then
37 return 1
38 else
39 return 0
40 end
41 end
42
43 redef fun iterator do return new IteratorRange[E](self)
44
45 redef fun iterate
46 !each(e: E)
47 do
48 var c = _first
49 var l = _last
50 while c <= l do
51 each(c)
52 c = c.succ
53 end
54 end
55
56 redef fun length
57 do
58 var nb = _first.distance(_after)
59 if nb > 0 then
60 return nb
61 else
62 return 0
63 end
64 end
65
66 redef fun is_empty do return _first >= _after
67
68 # Create a range [`from', `to'].
69 # The syntax [`from'..`to'[ is equivalent.
70 init(from: E, to: E)
71 do
72 _first = from
73 _last = to
74 _after = to.succ
75 end
76
77 # Create a range [`from', `to'[.
78 # The syntax [`from'..`to'[ is equivalent.
79 init without_last(from: E, to: E)
80 do
81 _first = from
82 _last = to.prec
83 _after = to
84 end
85 end
86
87 class IteratorRange[E: Discrete]
88 # Iterator on ranges.
89 super Iterator[E]
90 var _range: Range[E]
91 redef readable var _item: E
92
93 redef fun is_ok do return _item < _range.after
94
95 redef fun next do _item = _item.succ
96
97 init(r: Range[E])
98 do
99 _range = r
100 _item = r.first
101 end
102 end