4 ms·
Portable tail recursion for Common Lisp: http://www.kylheku.com/cgit/lisp-snippets/tree/tail-recursion.lisp http://www.kylheku.com/cgit/lisp-snippets/tree/tail
by kazinator 11y ago
Portable tail recursion for Common Lisp:
http://www.kylheku.com/cgit/lisp-snippets/tree/tail-recursion.lisp http://www.kylheku.com/cgit/lisp-snippets/tree/tail-recursio...
The lexical tlet construct doesn't use trampolines; it translates to tagbody/go. It is built on the argtags macro (early in the file), which provides an abstraction similar to tagbody/go, but where the labels can take parameters, and GO passes parameters to labels. The parameters are just variable assignments, of course. If you (goto foo 1 2 3) and there is a (label foo x y z), it means that control passes to that label, and the variables x y z take on values 1 2 3.
deftail is for tail recursion among independent functions. It is based on trampolines. The :other-tails keyword is used to declare which other functions participate. When the deftail function calls these others, those calls are assumed to be tail calls. You can also use the tail-call function explicitly (as a replacement for funcall) to abandon execution up to the trampoline loop and call a given function.
tail-call is the heart of the trampoline. It first checks whether it is already dynamically enclosed in a trampoline, and if so, it just uses that one to do the tail call. Otherwise it establishes a new dynamic contour and enters into the trampoline loop.
Thus any of the tail functions can be entered as ordinary functions. Then when they tail out to their peers, they establish the trampoline context.
- junke 11y agoThanks for sharing this.