Skip to content

Instantly share code, notes, and snippets.

@zummenix
Created January 25, 2016 10:41
Show Gist options
  • Save zummenix/6b082d6573527c31a5b1 to your computer and use it in GitHub Desktop.
Save zummenix/6b082d6573527c31a5b1 to your computer and use it in GitHub Desktop.
Lazy evaluation prototype written in rust.
fn main() {
let mut a = lazy(|| {
println!("Hello");
546 + 233
});
println!("{:?}", a.value());
println!("{:?}", a.value());
println!("{:?}", a.value());
}
fn lazy<T, F>(f: F) -> Lazy<T, F> where F: FnOnce() -> T {
Lazy { storage: Some(Storage::Func(f)) }
}
struct Lazy<T, F> {
storage: Option<Storage<T, F>>,
}
impl<T, F> Lazy<T, F> where F: FnOnce() -> T {
fn value(&mut self) -> &T {
let s = self.storage.take().unwrap().init_if_needed();
self.storage = Some(s);
self.storage.as_ref().unwrap().value()
}
}
enum Storage<T, F> {
Value(T),
Func(F),
}
impl<T, F> Storage<T, F> where F: FnOnce() -> T {
fn init_if_needed(self) -> Self {
match self {
Storage::Value(v) => Storage::Value(v),
Storage::Func(f) => Storage::Value((f)()),
}
}
fn value(&self) -> &T {
match *self {
Storage::Value(ref v) => v,
_ => unreachable!(),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment