syntax: 'meth' -> 'fun', 'attr' -> 'var'
[nit.git] / lib / standard / 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 special 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 length
46 do
47 var nb = _first.distance(_after)
48 if nb > 0 then
49 return nb
50 else
51 return 0
52 end
53 end
54
55 redef fun is_empty do return _first >= _after
56
57 # Create a range [`from', `to'].
58 # The syntax [`from'..`to'[ is equivalent.
59 init(from: E, to: E)
60 do
61 _first = from
62 _last = to
63 _after = to.succ
64 end
65
66 # Create a range [`from', `to'[.
67 # The syntax [`from'..`to'[ is equivalent.
68 init without_last(from: E, to: E)
69 do
70 _first = from
71 _last = to.prec
72 _after = to
73 end
74 end
75
76 class IteratorRange[E: Discrete]
77 # Iterator on ranges.
78 special Iterator[E]
79 var _range: Range[E]
80 redef readable var _item: E
81
82 redef fun is_ok do return _item < _range.after
83
84 redef fun next do _item = _item.succ
85
86 init(r: Range[E])
87 do
88 _range = r
89 _item = r.first
90 end
91 end