On Lisp15章。マクロで遅延評価を実装
(defconstant unforced (gensym))
(defstruct delay forced closure)
(defmacro delay (expr)
(let ((self (gensym)))
`(let ((,self (make-delay :forced unforced)))
(setf (delay-closure ,self)
#'(lambda () (setf (delay-forced ,self) ,expr))) ,self)))
(defun force(x)
(if (delay-p x)
(if (eq (delay-forced x) unforced)
(funcall (delay-closure x))
(delay-forced x))
x))
これを使う場合
(let ((x 2))
(setq d (delay (1+ x))))
そのままでは評価されない
d
#S(DELAY :FORCED #:G748 :CLOSURE #<CLOSURE (LAMBDA #) {12234AF5}>)
forceしてやる
(force d)
3