Mercurial > hg > ishara
diff general/funutils/lazy.m @ 4:e44f49929e56
Adding reorganised general toolbox, now in several subdirectories.
author | samer |
---|---|
date | Sat, 12 Jan 2013 19:21:22 +0000 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/general/funutils/lazy.m Sat Jan 12 19:21:22 2013 +0000 @@ -0,0 +1,27 @@ +% lazy - Lazy evaluator, or memoiser +% +% lazy :: (unit -> A) -> (unit -> A). +% lazy :: (unit -> action A) -> (unit -> action A). +% +% If x=lazy(f), then f is not called until x is +% called. Then x() returns x1=f(). Thereafter, +% x() returns x1 and f is never called again. +% +% Eg, let x=lazy(@()rand). +% Then x() returns the same random number each +% time it is called. +function f=lazy(thunk) + value=thunk; + evalled=false; + f=@get; + + function v=get, + if evalled, + v=value; + else + value=thunk(); + evalled=true; + v=value; + end + end +end