tailcall(3tcl)
π« tailcall β the glow-up where your proc becomes a whole other command π«
okay bestie, welcome to tailcall(3tcl), a Tcl Built-In Commands moment β¨ this one lives in the Tcl 8.6 era and it is so underrated, fr fr.
π NAME π
tailcall β swap the procedure you're literally in the middle of running for a whole different command, no cap π
πΈ SYNOPSIS πΈ
tailcall command ?arg ...?
β¨ DESCRIPTION β¨
so here's the tea β β tailcall replaces the procedure, lambda application, or method that's currently executing with another command. like, you were that proc, and now you're that other command. iconic behaviour, honestly π
the command you hand it? if you also pass arg ..., those get passed along as its arguments. and here's the part that matters, bestie β it gets looked up in the current namespace context, NOT in the caller's. that's the one and only difference in resolution. apart from that little twist, it is fully equivalent to this:
return [uplevel 1 [list command ?arg ...?]]
and now the part where you have to be careful, because we do not play games with the stack π
tailcallmay not be invoked from within anuplevelinto a procedure, or inside acatchinside a procedure or lambda. just don't. it's giving undefined-vibes and we're not doing that today π
π¦ EXAMPLE π¦
first up: compute the factorial of a number π
proc factorial {n {accum 1}} {
if {$n < 2} {
return $accum
}
tailcall factorial [expr {$n - 1}] [expr {$accum * $n}]
}
next one, and this is lowkey my favourite β print the elements of a list, with alternating lines getting different indentations π
proc printList {theList} {
if {[llength $theList]} {
puts "> [lindex $theList 0]"
tailcall printList2 [lrange $theList 1 end]
}
}
proc printList2 {theList} {
if {[llength $theList]} {
puts "< [lindex $theList 0]"
tailcall printList [lrange $theList 1 end]
}
}
see how they just keep swapping into each other? mutual main character energy, we love to see it π
π SEE ALSO π
β KEYWORDS β
- call
- recursion
- tail recursion
and that's the whole page, bestie π«Ά this was tailcall(3tcl) from the Tcl Built-In Commands crew, riding with Tcl 8.6 and stamped with the date tailcall(3tcl) down at the bottom. go make some tail calls, you absolute legend πβ¨π§
π¦ where this page comes from
- debian bookworm: tcl8.6-doc 8.6.13+dfsg-2
- debian trixie: tcl8.6-doc 8.6.16+dfsg-1
- debian trixie: tcl9.0-doc 9.0.1+dfsg-2
- ubuntu jammy: tcl8.6-doc 8.6.12+dfsg-1build1
- ubuntu noble: tcl8.6-doc 8.6.14+dfsg-1build1
- ubuntu questing: tcl8.6-doc 8.6.17+dfsg-1
- ubuntu questing: tcl9.0-doc 9.0.2+dfsg-1
- ubuntu resolute: tcl8.6-doc 8.6.17+dfsg-1build1
- ubuntu resolute: tcl9.0-doc 9.0.3+dfsg-1
- ubuntu stonking: tcl8.6-doc 8.6.18+dfsg-1
- ubuntu stonking: tcl9.0-doc 9.0.4+dfsg-1
- Copyright (c) 1993 The Regents of the University of California
- Copyright (c) 1994-1996 Sun Microsystems, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms