Skip to content

Instantly share code, notes, and snippets.

@53ningen
Created August 17, 2016 12:47
Show Gist options
  • Save 53ningen/1e8f4615cfb4ffb85aaca5e6c051cbfe to your computer and use it in GitHub Desktop.
Save 53ningen/1e8f4615cfb4ffb85aaca5e6c051cbfe to your computer and use it in GitHub Desktop.
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