calculator: intro android UI
[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 module range
15
16 import abstract_collection
17
18 # Range of discrete objects.
19 class Range[E: Discrete]
20 super Collection[E]
21
22 redef var first: E
23
24 # Get the last element.
25 var last: E
26
27 # Get the element after the last one.
28 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 or is_empty
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.successor(1)
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.predecessor(1)
72 after = to
73 end
74 end
75
76 private class IteratorRange[E: Discrete]
77 # Iterator on ranges.
78 super Iterator[E]
79 private var range: Range[E]
80 redef var item is noinit
81
82 redef fun is_ok do return _item < _range.after
83
84 redef fun next do _item = _item.successor(1)
85
86 init
87 do
88 _item = _range.first
89 end
90 end
91
92 redef class Int
93 # Returns the range from 0 to `self-1`, is used to do:
94 #
95 # var s = new Array[String]
96 # for i in 3.times do s.add "cool"
97 # assert s.join(" ") == "cool cool cool"
98 #
99 # s.clear
100 # for i in 10.times do s.add(i.to_s)
101 # assert s.to_s == "0123456789"
102 fun times: Range[Int] do return [0 .. self[
103 end