public
Created

Thunks in Rust

  • Download Gist
lazy.rs
Rust
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
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);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.