, , , () , , ( , ). , , . Common Lisp:
(defstruct thunk closure)
(defmacro thunk (&body body)
`(make-thunk :closure (lambda () ,@body)))
(defun trampoline (thunk)
(do ((thunk thunk (funcall (thunk-closure thunk))))
((not (thunk-p thunk)) thunk)))
, thunk, . , . thunk, , , , thunk. , mapcar:
(defun t-mapcar1 (function list)
(labels ((m (list acc)
(if (endp list)
(nreverse acc)
(thunk
(m (rest list)
(list* (funcall function (first list)) acc))))))
(m list '())))
, :
CL-USER> (t-mapcar1 '1+ '())
NIL
, thunk:
CL-USER> (t-mapcar1 '1+ '(1 2))
#S(THUNK :CLOSURE
, ( , ):
CL-USER> (trampoline (t-mapcar1 '1+ '()))
NIL
CL-USER> (trampoline (t-mapcar1 '1+ '(1 2)))
(2 3)
CL-USER> (trampoline (t-mapcar1 '1+ '(1 2 3 4)))
(2 3 4 5)
, ,
(defun fn (x)
(when x
(princ x)
(jump 'fn (cdr x)))
(rest))
. return fn, thunk "" , .
(defun fn (x)
(when x
(princ x)
(return (thunk (fn (cdr x)))))
(rest))