Skip to content

Instantly share code, notes, and snippets.

@ConnyOnny
Created December 27, 2016 01:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ConnyOnny/5917e4e549056f6a3db01a5277480f6b to your computer and use it in GitHub Desktop.
Save ConnyOnny/5917e4e549056f6a3db01a5277480f6b to your computer and use it in GitHub Desktop.
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