tree->generator with explicit CPS
2008-09-03
This is just a little follow-up to my last post. As another exercise in continuations, I transformed tree->generator to explicit continuation-passing style. I guess I could also have looked at the expansions of the cl-cont macros, but this is the result of a manual transformation:
(defun tree->generator (tree)
(let (generate-leaves)
(setf generate-leaves
(lambda ()
(labels ((recur (tree cont)
(cond ((null tree) ; empty leaf: continue.
(funcall cont))
((consp tree) ; recurse into branches:
(recur (car tree)
(lambda ()
(recur (cdr tree) cont))))
('otherwise ; leaf with a value:
(setf generate-leaves ; update generator
cont)
tree)))) ; and return the value.
(recur tree
(lambda () nil))))) ; return nil after exhaustion.
(lambda ()
(funcall generate-leaves))))
[EDIT: I realized the potential for further simplification right after publishing the post. So now the call to and return from generate-leaves in the above code aren't in CPS anymore, only recur has to be in CPS.]