Created
December 6, 2012 04:57
-
-
Save stevej/4221872 to your computer and use it in GitHub Desktop.
Thunks in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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