Skip to content

Instantly share code, notes, and snippets.

@yashigani
Created August 27, 2015 00:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yashigani/ab7c51cc4793b42ea1df to your computer and use it in GitHub Desktop.
Save yashigani/ab7c51cc4793b42ea1df to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment