Skip to content

Instantly share code, notes, and snippets.

@asaaki
Created June 12, 2020 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asaaki/c28c4f40752b36c7fbdc5980be8096bf to your computer and use it in GitHub Desktop.
Save asaaki/c28c4f40752b36c7fbdc5980be8096bf to your computer and use it in GitHub Desktop.
TCO #rustlang #recursion
// Recursion: TCO (Tail Call Optimization)
// Computerphile: https://www.youtube.com/watch?v=_JtPhF8MshA
fn fib(n: usize) -> usize {
fib_go(n, 0, 1)
}
fn fib_go(n: usize, a: usize, b: usize) -> usize {
match (n, a, b) {
(0, v, _) => return v,
(1, _, v) => return v,
(n, x, y) => fib_go(n - 1, y, x + y)
}
}
fn main() {
let n = 11;
println!("fib({}) = {}", n, fib(n)); // 89
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment