Skip to content

Instantly share code, notes, and snippets.

@archer884
Created December 16, 2014 01:10
Show Gist options
  • Save archer884/f6e3388abcfba200ec14 to your computer and use it in GitHub Desktop.
Save archer884/f6e3388abcfba200ec14 to your computer and use it in GitHub Desktop.
Clojure-style trampoline using boxing
#![feature(unboxed_closures)]
use Bounce::{Process, Result};
fn main() {
let x: int = from_str(std::os::args()[1].as_slice()).unwrap();
let result = Process(box move || is_even(x)).execute();
println!("{}", if result { "even" } else { "odd" });
}
fn is_even(n: int) -> Bounce<bool> {
match n {
0i => Result(true),
n => Process(box move || is_odd(n - 1))
}
}
fn is_odd(n: int) -> Bounce<bool> {
match n {
0i => Result(false),
n => Process(box move || is_even(n - 1))
}
}
enum Bounce<R> {
Process(Box<Fn() -> Bounce<R> + 'static>),
Result(R),
}
impl<R> Bounce<R> {
fn execute(mut self) -> R {
loop {
match self {
Process(exec) => { self = exec.call(()); },
Result(value) => { return value; }
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment