1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2013-2014 Alexis Laferrière <alexis.laf@xymus.net>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Advanced services for `Numeric` types
24 # Get the numeric version of `self`
26 # require: `is_numeric`
29 # assert "0".to_n == 0
30 # assert "0.0".to_n == 0.0
31 # assert ".12345".to_n == 0.12345
32 # assert "12345".to_n == 12345
37 if is_empty
then return 0
38 if chars
.has
('.') then return to_f
43 redef interface Numeric
44 # Universal `+` with any `Numeric`
47 # assert 1.add(1) == 2
48 # assert 1.add(0.1) == 1.1
49 # assert 1.1.add(1.1) == 2.2
50 # assert 1.1.add(1) == 2.1
52 fun add
(other
: Numeric): Numeric is abstract
54 # Universal `-` with any `Numeric`
57 # assert 2.sub(1) == 1
58 # assert 1.sub(0.1) == 0.9
59 # assert 1.1.sub(0.1) == 1.0
60 # assert 2.1.sub(1) == 1.1
62 fun sub
(other
: Numeric): Numeric is abstract
64 # Universal `/` with any `Numeric`
67 # assert 8.div(2) == 4
68 # assert 4.div(0.5) == 8.0
69 # assert 1.1.div(0.1) == 11.0
70 # assert 2.2.div(2) == 1.1
72 fun div
(other
: Numeric): Numeric is abstract
74 # Universal `*` with any `Numeric`
77 # assert 2.mul(4) == 8
78 # assert 11.mul(0.1) == 1.1
79 # assert 11.1.mul(0.1) == 1.11
80 # assert 1.1.mul(4) == 4.4
82 fun mul
(other
: Numeric): Numeric is abstract
88 if other
isa Float then
91 return self + other
.as(Int)
97 if other
isa Float then
100 return self - other
.as(Int)
106 if other
isa Float then
109 return self * other
.as(Int)
115 if other
isa Float then
117 else if other
isa Int then
118 if other
== 0 then return self.to_f
/ 0.0
124 redef universal Float
125 redef fun add
(other
) do return self + other
.to_f
126 redef fun sub
(other
) do return self - other
.to_f
127 redef fun div
(other
) do return self / other
.to_f
128 redef fun mul
(other
) do return self * other
.to_f