-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathfraction.blink
71 lines (54 loc) · 2.43 KB
/
fraction.blink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/// A class for handling fractions.
class Fraction(n: Int, d: Int) {
// The 'Math' object contains methods for
// mathematical operations.
// e.g Math.abs(), Math.max(), Math.min(),
// Math.random(), ...
var g: Int = gcd(Math.abs(n), Math.abs(d))
var num: Int = n / g
var den: Int = d / g
func num(): Int = num
func setNum(n: Int) = num = n / gcd(Math.abs(n), Math.abs(den))
func den(): Int = den
func setDen(d: Int) = den = d / gcd(Math.abs(num), Math.abs(d))
// Redefines the + operation between 2 Fraction objects.
func +(that: Fraction): Fraction = new Fraction(
num * that.den() + den * that.num(),
den * that.den()
)
// Redefines the + operation between a Fraction and an Int.
func +(that: Int): Fraction = this + new Fraction(that, 1)
// Redefines the - operation between 2 Fraction objects.
func -(that: Fraction): Fraction = new Fraction(
num * that.den() - den * that.num(),
den * that.den()
)
// Redefines the - operation between a Fraction and an Int.
func -(that: Int): Fraction = this - new Fraction(that, 1)
// Redefines the * operation between 2 Fraction objects.
func *(that: Fraction): Fraction = new Fraction(num * that.num(), den * that.den())
// Redefines the * operation between 2 Fraction objects.
func *(that: Int): Fraction = this * new Fraction(that, 1)
// Redefines the * operation between 2 Fraction objects.
func /(that: Fraction): Fraction = this * new Fraction(that.den(), that.num())
// Redefines the / operation between 2 Fraction objects.
func /(that: Int): Fraction = this / new Fraction(that, 1)
// Overrides the == operation from Object class.
override func ==(that: Object): Bool = {
// The instanceOf() function checks if an object
// is an instance of the specified type.
if (!that.instanceOf("Fraction"))
false
else {
// The as keyword is used to cast an object of one type
// to another type.
let frac = that as Fraction in {
num == frac.num() && den == frac.den()
}
}
}
// Overrides toString() from Object class.
override func toString(): String = num + if (den > 1) "/" + den else ""
// Private function to compute the GCD of two integers.
private func gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
}