Instantly share code, notes, and snippets.

yashigani/natural-number.swift Created Aug 27, 2015

My live coding in #関モバ
 enum N { case Zero indirect case Succ(N) static func succ(n: N) -> N { return .Succ(n) } } let zero: N = .Zero let one: N = .Succ(.Zero) let two: N = .Succ(.Succ(.Zero)) let three: N = N.succ(two) extension N { init(from: UInt) { self = Repeat(count: Int(from), repeatedValue: N.succ).reduce(.Zero) { \$1(\$0) } } } let _two: N = N(from: 2) extension N: Equatable, Comparable {} func ==(lhs: N, rhs: N) -> Bool { switch (lhs, rhs) { case (.Zero, .Zero): return true case let (.Succ(a), .Succ(b)): return a == b default: return false } } func <(lhs: N, rhs: N) -> Bool { switch (lhs, rhs) { case (.Zero, .Succ(_)): return true case let (.Succ(a), .Succ(b)): return a < b default: return false } } two == _two two == zero two < one one <= one func +(lhs: N, rhs: N) -> N { switch (lhs, rhs) { case (let a, .Zero): return a case let (a, .Succ(b)): return .Succ(a + b) } } one + two + three extension N: CustomStringConvertible { var description: String { func toInt(n: N) -> Int { switch n { case .Zero: return 0 case let .Succ(a): return 1 + toInt(a) } } return "\(toInt(self))" } } func *(lhs: N, rhs: N) -> N { switch (lhs, rhs) { case (_, .Zero): return .Zero case let (a, .Succ(b)): return a * b + a } } two * three two * zero zero * two