Created
December 27, 2016 01:26
-
-
Save ConnyOnny/5917e4e549056f6a3db01a5277480f6b to your computer and use it in GitHub Desktop.
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
enum FacResult { | |
Become(i32,i32), | |
Return(i32), | |
} | |
fn fac_tail(n: i32, accu: i32) -> FacResult { | |
if n < 2 { | |
// result known | |
FacResult::Return(accu) | |
} else { | |
// the recursion case | |
FacResult::Become(n-1, accu*n) | |
} | |
} | |
fn fac_trampoline(n: i32) -> i32 { | |
let mut result = FacResult::Become(n,1); | |
while let FacResult::Become(n, accu) = result { | |
result = fac_tail(n, accu); | |
} | |
if let FacResult::Return(v) = result { | |
v | |
} else { | |
unreachable!() | |
} | |
} | |
fn main() { | |
println!("fac(5) = {}", fac_trampoline(5)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment