view general/funutils/lazy.m @ 61:eff6bddf82e3 tip

Finally implemented perceptual brightness thing.
author samer
date Sun, 11 Oct 2015 10:20:42 +0100
parents e44f49929e56
children
line wrap: on
line source
% 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