Last active
August 29, 2015 14:11
-
-
Save archer884/1c66d306ce0d07e5df12 to your computer and use it in GitHub Desktop.
Trampoline implementation in Rust
This file contains hidden or 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
| #![feature(unboxed_closures)] | |
| fn main() { | |
| let x = from_str::<int>(std::os::args()[1].as_slice()).unwrap(); | |
| let n = Bounce::Incomplete(x).execute(|n| { | |
| match n { | |
| n if n < 1 => Bounce::Fault("Value out of range."), | |
| 1i => Bounce::Complete(n), | |
| n => Bounce::Incomplete(n - 1i), | |
| } | |
| }); | |
| println!("{}", n); | |
| } | |
| enum Bounce<R> { | |
| Incomplete(R), | |
| Complete(R), | |
| Fault(&'static str), | |
| } | |
| impl<R> Bounce<R> { | |
| fn execute(mut self, f: |R| -> Bounce<R>) -> R { | |
| loop { | |
| match self { | |
| Bounce::Incomplete(value) => { self = f(value); }, | |
| Bounce::Complete(value) => { return value; }, | |
| Bounce::Fault(message) => { panic!(message); }, | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment