Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created September 27, 2018 01:24
Show Gist options
  • Save rust-play/25d5e3b596fe1fc81a51e5b4fc4e760f to your computer and use it in GitHub Desktop.
Save rust-play/25d5e3b596fe1fc81a51e5b4fc4e760f to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
enum RecursionResult<C, R> {
Continue(C),
Return(R),
}
fn tail_recurse<C, R>(mut init: C, mut f: impl FnMut(C) -> RecursionResult<C, R>) -> R {
loop {
match f(init) {
RecursionResult::Continue(c) => init = c,
RecursionResult::Return(r) => return r,
}
}
}
pub fn factorial(x: usize) -> usize {
tail_recurse((x, 1), |(a, b)| {
if a == 0 {
RecursionResult::Return(b)
} else {
RecursionResult::Continue((a - 1, a * b))
}
})
}
pub fn factorial2(x: usize) -> usize {
(1..=x).product()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment