[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Does Lua support Lazy Evaluation?
- From: Bret Victor <bret@...>
- Date: Sat, 9 Dec 2006 18:23:37 +0000 (UTC)
Alex Queiroz <asandroq <at> gmail.com> writes:
> I thought Scheme is strict as well?
Scheme's "delay" is a macro that wraps up an expression inside a lambda,
so it's not evaluated until "forced":
(delay (+ 1 2)) turns into (lambda () (+ 1 2))
(force promise) turns into (promise)
In Lua, it would be something like:
promise = delay(1 + 2) turns into
promise = function () return 1 + 2 end
three = force(promise) turns into
three = promise()
The force function, of course, can be just a normal function, but delay
has to be a macro or treated specially somehow.
I've always felt that "delay" was superfluous syntax, and that's it's
perfectly clear to just use plain old lambda (or in the Lua case,
One advantage of "delay" is that you can transparently hide memoization
inside it, which is necessary for proper laziness, but that's pretty
easy to do even without special syntax:
function mem (f)
return function ()
if f then v = f(); f = nil end
promise = mem(function () return 1 + 2 end)
three = promise() -- calculates and memoizes 1 + 2
three = promise() -- returns the memoized value
I do feel that special syntax is badly needed to replace the bulky
function (x) return expr end. Fabien uses a Smalltalk/Ruby-ish
|x| expr, which I think is great.