Proper TailcallsMiguel SoferDavid S. Cargo$Revision: 1.8 $tailcall NRE
This TIP recommends adding proper tailcalls to Tcl.
We propose to add a new command:
tailcall cmd ?arg ...?
The command can only be invoked in a procedure or lambda body.
The effect of this command is very similar to:
return [uplevel 1 [list [namespace which cmd ] ?arg ...?]]
with the sole exception that the invocation of cmd happens after the currently executing body returns and is not visible in Tcl's call stack.
The new Non-Recursive Engine (NRE) implemented in Tcl 8.6 allows support for a number of interesting features that have previously been difficult or impossible to implement efficiently in Tcl. One such feature is support for proper tailcalls, an important feature for functional-style programming. The new command allows unbounded recursion and enables programming in continuation passing style.
tailcall is implemented as a new command, as opposed to an optimization that would be done automatically by the bytecode compiler, due to the effect it has on Tcl's call stack.
Consider the following example:
IHByb2Mgc2hvd1N0YWNrIHt9IHs=ICAgICBzZXQgZGVwdGggW2luZm8gZnJhbWVdICAgICBzZXQgcmVzIHt9ICAgICBmb3Ige3NldCBpIDF9IHskaSA8PSAkZGVwdGh9IHtpbmNyIGl9IHs=IAlsYXBwZW5kIHJlcyBbaW5mbyBmcmFtZSAkaV0=ICAgICB9ICAgICByZXR1cm4gJHJlcw==IH0=IA==IHByb2Mgb25lIGNtZCB7am9pbiBbJGNtZF0gXG59IHByb2MgdHdvIHt9IHt1cGxldmVsIDEgc2hvd1N0YWNrfQ==IHByb2MgdGhyZWUge30ge3RhaWxjYWxsIHNob3dTdGFja30=
When run at the interactive prompt, we obtain
ICUgb25lIHR3bw==IHR5cGUgZXZhbCBsaW5lIDEgY21kIHtvbmUgdHdvfSBsZXZlbCAyIHR5cGUgcHJvYyBsaW5lIC0xIGNtZCB7JGNtZH0gcHJvYyA6Om9uZSBsZXZlbCAxIHR5cGUgcHJvYyBsaW5lIDEgY21kIHt1cGxldmVsIDEgc2hvd1N0YWNrfSBwcm9jIDo6dHdvIHR5cGUgZXZhbCBsaW5lIDEgY21kIHNob3dTdGFjayBwcm9jIDo6dHdvIHR5cGUgcHJvYyBsaW5lIDUgY21kIHtpbmZvIGZyYW1lICRpfSBwcm9jIDo6c2hvd1N0YWNrIGxldmVsIDA=ICUgb25lIHRocmVlIHR5cGUgZXZhbCBsaW5lIDEgY21kIHtvbmUgdGhyZWV9IGxldmVsIDI=IHR5cGUgcHJvYyBsaW5lIC0xIGNtZCB7JGNtZH0gcHJvYyA6Om9uZSBsZXZlbCAxIHR5cGUgcHJvYyBsaW5lIDUgY21kIHtpbmZvIGZyYW1lICRpfSBwcm9jIDo6c2hvd1N0YWNrIGxldmVsIDA=ICUg
Remark how tailcall completely removed the proc three from Tcl's call stack. This effect is also apparent on error traces.
An experimental implementation of tailcalls is available in Tcl 8.6a2 in CVS on sourceforge, in the ::tcl::unsupported namespace.
This document has been placed in the public domain.