Created
August 17, 2016 12:47
-
-
Save 53ningen/1e8f4615cfb4ffb85aaca5e6c051cbfe to your computer and use it in GitHub Desktop.
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
indirect enum TailRec<T> { | |
case Done(T) | |
case More(() -> TailRec<T>) | |
func run() -> T { | |
var tailRec = self | |
while true { | |
switch tailRec { | |
case .More(let next): tailRec = next() | |
case .Done(let t): return t | |
} | |
} | |
} | |
} | |
let done = TailRec.Done(10) | |
done.run() | |
let more = TailRec.More({ _ in .Done(10) }) | |
more.run() | |
func tri(n: UInt, acc: UInt = 0) -> UInt { | |
func loop(n: UInt, acc: TailRec<UInt>) -> TailRec<UInt> { | |
if n < 2 { | |
return .Done(n + acc.run()) | |
} else { | |
return .More({ _ in | |
loop(n: n - 1, acc: .Done(acc.run() + n)) | |
}) | |
} | |
} | |
return loop(n: n, acc: .Done(0)).run() | |
} | |
tri(n: 100000) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment