Created
September 27, 2018 01:24
-
-
Save rust-play/25d5e3b596fe1fc81a51e5b4fc4e760f to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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 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