Skip to content

Instantly share code, notes, and snippets.

@stevej
Created December 6, 2012 04:57
Show Gist options
  • Save stevej/4221872 to your computer and use it in GitHub Desktop.
Save stevej/4221872 to your computer and use it in GitHub Desktop.
Thunks in Rust
use core::option;
/**
* Implementation of thunks in Rust.
*/
pub struct Lazy<T> {
code : @fn() -> T,
mut value : Option<T>
}
/**
* Unfortunately requires a caller to make a closure.
*/
pure fn Lazy<T>(closure: @fn() -> T) -> Lazy<T> {
let l : Lazy<T> = Lazy {
code : closure,
value : None
};
return l;
}
impl<T> Lazy<T> {
fn force() -> T {
match self.value {
Some(value) => { return value; }
None => {
let result = self.code();
self.value = Some(result);
return result;
}
};
}
}
#[test]
fn test_create_thunk() {
let mut a : int = 10;
// thunk is a Lazy<()>.
// trying to call Lazy<int> (|| ...
// results in `error: unresolved name: int`
let thunk = Lazy (|| {
a + 10;
});
let z = thunk.force();
// lazy.rs:50:26: 50:28 error: mismatched types: expected `()` but found `<VI2>` (expected () but found integral variable)
assert(thunk.force() == 20);
a = 100;
assert(thunk.force() == 20);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment