lazy programming

41 views
Skip to first unread message

Paulo Geyer

unread,
Apr 23, 2011, 6:27:25 PM4/23/11
to Land of Lisp
Hi,

I've got confused with the lazy macro and force function from the 18
chapter,

(defmacro lazy (&body body)
(let ((forced (gensym))
(value (gensym)))
`(let ((,forced nil)
(,value nil))
(lambda ()
(unless ,forced
(setf ,value (progn ,@body))
(setf ,forced t))
,value))))

(defun force (lazy-value)
(funcall lazy-value))

but, why funcall bypass the unless condition? Shouldn't it just call
the function returned from the macro, and the unless condition return
false?

Paulo Geyer

unread,
Apr 23, 2011, 6:58:03 PM4/23/11
to Land of Lisp
huh, there's nothing wrong.
(unless ,forced) only evaluates the code if it isn't true, which works
fine for this situation.

Conrad

unread,
Apr 23, 2011, 7:03:08 PM4/23/11
to Land of Lisp
Yeah, if I understand your question:

The expectation is that "force" may be called multiple times on the
same value. The first time this happens, the variable 'forced will be
nil, so that the "unless" statement is triggered. However, the next
time we force the same value, 'forced will be 't, so this part is
skipped. ('forced will be 't because that variable is created outside
of the lambda, which causes a closure to be created by the lambda
which causes the lambda to capture, and remember that variable.)
Reply all
Reply to author
Forward
0 new messages