Skip to content

Instantly share code, notes, and snippets.

@archer884
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save archer884/1c66d306ce0d07e5df12 to your computer and use it in GitHub Desktop.

Select an option

Save archer884/1c66d306ce0d07e5df12 to your computer and use it in GitHub Desktop.
Trampoline implementation in Rust
#![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