Created
June 12, 2020 17:41
-
-
Save asaaki/c28c4f40752b36c7fbdc5980be8096bf to your computer and use it in GitHub Desktop.
TCO #rustlang #recursion
This file contains 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
// 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