-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContents.swift
71 lines (47 loc) · 1.45 KB
/
Contents.swift
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
//: Playground - noun: a place where people can play
import UIKit
struct Rational: CustomStringConvertible {
var numer: Int = 0
var denom: Int = 1
var description: String {
let greatestCommonDivisior = gcd(numer, denom)
return "\(numer / greatestCommonDivisior)/\(denom / greatestCommonDivisior)"
}
init?(numer: Int, denom: Int) {
guard denom != 0 else {
return nil
}
//assert(denom != 0)
self.numer = numer
self.denom = denom
}
init(value: Int) {
numer = value
}
func max(that: Rational) -> Rational {
return self < that ? that : self
}
private func gcd(a: Int, _ b: Int) -> Int {
return b == 0 ? a : gcd(b, a % b)
}
}
func + (left: Rational, right: Rational) -> Rational {
return Rational(numer: left.numer * right.denom + right.numer * left.denom,
denom: right.denom * left.denom)!
}
func - (left: Rational, right: Rational) -> Rational {
let negativeRight = -right
return left + negativeRight
}
prefix func - (r: Rational) -> Rational {
return Rational(numer: r.numer, denom: r.denom)!
}
infix operator < { associativity right precedence 110 }
func < (left: Rational, right: Rational) -> Bool {
return left.numer * right.numer < right.numer * left.denom
}
let a = Rational(numer: 24, denom: 6)!
let b = Rational(value: 4)
a < b
a + b
-b