Skip to content

Instantly share code, notes, and snippets.

@pchlupacek
Last active December 26, 2016 07:45
Show Gist options
  • Save pchlupacek/4845a828f17502d474d229bae9ed3b2f to your computer and use it in GitHub Desktop.
Save pchlupacek/4845a828f17502d474d229bae9ed3b2f to your computer and use it in GitHub Desktop.
pub enum Trampoline<A> {
Return(A)
, Suspend(Box<Fn() -> Trampoline<A>>)
}
impl<A> Trampoline<A> {
pub fn now(a:A) -> Trampoline<A> {
Trampoline::Return(a)
}
pub fn suspend<F>(thunk: F) -> Trampoline<A>
where F: Fn() -> Trampoline<A> {
Trampoline::Suspend(Box::new(thunk()))
}
pub fn map<B, F>(self, f: F) -> Trampoline<B>
where F: Fn(A) -> B {
self.flatMap(|a| Trampoline::Return(f(a)))
}
pub fn flatMap<B, F>(self, f: F) -> Trampoline<B>
where F: Fn(A) -> Trampoline<B> {
match self {
Trampoline::Return(a) => {
let eval = || -> Trampoline<B> { f(a) };
Trampoline::Suspend (Box::new(eval))
}
, Trampoline::Suspend(thunk) => {
let eval = || -> Trampoline<B> {
let a = thunk().run();
f(a)
};
Trampoline::Suspend (Box::new(eval))
}
}
}
pub fn run(self) -> A {
unimplemented!()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment