Created
January 20, 2019 21:57
-
-
Save guoye-zhang/b8c82b077d13020d9e48aa9ca8be3b3b to your computer and use it in GitHub Desktop.
Representing Peano integers using only Swift Optional
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func toPeano(_ n: Int) -> Any { | |
precondition(n >= 0) | |
if n == 0 { | |
return nil as Any? | |
} else { | |
return toPeano(n - 1) as Any? | |
} | |
} | |
protocol OptionalProtocol { | |
var isNil: Bool { get } | |
var unwrapped: Any { get } | |
} | |
extension Optional: OptionalProtocol { | |
var isNil: Bool { | |
return self == nil | |
} | |
var unwrapped: Any { | |
return self! | |
} | |
} | |
func fromPeano(_ n: Any) -> Int { | |
let n = n as! OptionalProtocol | |
if n.isNil { | |
return 0 | |
} | |
return fromPeano(n.unwrapped) + 1 | |
} | |
let p = toPeano(5) | |
fromPeano(p) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OptionalProtocol
is necessary becausen as! Any?
wraps n in an optional instead of casting it