Skip to content

Instantly share code, notes, and snippets.

@yashigani
Last active August 29, 2015 14:25
Show Gist options
  • Save yashigani/256fc717d42efc04230a to your computer and use it in GitHub Desktop.
Save yashigani/256fc717d42efc04230a to your computer and use it in GitHub Desktop.
indirectが実装されたのでSwiftで自然数を作りました
enum N {
case Zero
indirect case Succ(N)
init(_ n: UInt) {
switch n {
case 0: self = .Zero
default: self = .Succ(N(n - 1))
}
}
func toInt() -> UInt {
switch self {
case .Zero: return 0
case .Succ(let n): return 1 + n.toInt()
}
}
}
func +(lhs: N, rhs: N) -> N {
switch rhs {
case .Zero: return lhs
case .Succ(let n): return .Succ(lhs + n)
}
}
func *(lhs: N, rhs: N) -> N {
switch rhs {
case .Zero: return .Zero
case .Succ(let n): return lhs * n + lhs
}
}
// 0 + 1
print((N(0) + N(1)).toInt()) // => 1
// 2 + 3
print((N(2) + N(3)).toInt()) // => 5
// 2 * 3
print((N(2) * N(3)).toInt()) // => 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment