Skip to content

Instantly share code, notes, and snippets.

@oisdk
Created December 7, 2015 17:18
Show Gist options
  • Save oisdk/226578793c4ca55d02f6 to your computer and use it in GitHub Desktop.
Save oisdk/226578793c4ca55d02f6 to your computer and use it in GitHub Desktop.
infix operator /% {associativity right precedence 100 }
public struct Rational {
private let num, den: IntMax
}
public func /%(lhs: IntMax, rhs: IntMax) -> Rational {
let g = gcd(lhs,rhs)
let (n,d) = (lhs / g, rhs / g)
if d < 0 { return Rational(num: n * -1, den: d * -1) }
return Rational(num: n, den: d)
}
private func gcd(x: IntMax, _ y: IntMax) -> IntMax {
var (a,b) = (x,y)
while b != 0 { (a,b) = (b,a%b) }
return a
}
extension Rational: CustomStringConvertible {
public var description: String {
if den == 1 { return String(num) }
return String(num) + " / " + String(den)
}
}
extension Rational: Equatable {}
public func ==(lhs: Rational, rhs: Rational) -> Bool {
return lhs.num == rhs.num && lhs.den == rhs.den
}
public func +(lhs: Rational, rhs: Rational) -> Rational {
let g = gcd(lhs.den, rhs.den)
let d = (lhs.den * rhs.den) / g
return (lhs.num * (rhs.den/g) + rhs.num * (lhs.den/g)) /% d
}
public func *(lhs: Rational, rhs: Rational) -> Rational {
return (lhs.num*rhs.num) /% (lhs.den*rhs.den)
}
public func /(lhs: Rational, rhs: Rational) -> Rational {
return (lhs.num*rhs.den) /% (lhs.den*rhs.num)
}
public func -(lhs: Rational, rhs: Rational) -> Rational {
return lhs + Rational(num: rhs.num * -1, den: rhs.den)
}
extension Rational: Comparable {}
public func <(lhs: Rational, rhs: Rational) -> Bool {
return lhs.num * rhs.den < rhs.num * lhs.den
}
extension Rational: IntegerLiteralConvertible {
public init(integerLiteral value: IntMax) {
self = Rational(num: value, den: 1)
}
}
extension Rational: SignedNumberType {}
public prefix func -(x: Rational) -> Rational {
return Rational(num: x.num * -1, den: x.den)
}
extension Rational: Strideable {
public func distanceTo(other: Rational) -> Rational {
return other - self
}
public func advancedBy(n: Rational) -> Rational {
return self + n
}
}
extension Rational {
public var double: Double {
return Double(num) / Double(den)
}
}
infix operator ** { associativity left precedence 130 }
public func **<I: ForwardIndexType where I: IntegerLiteralConvertible>(lhs: Rational, rhs: I) -> Rational {
return (0..<rhs).reduce(1) { (a,_) in a * lhs }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment