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 πŸ™ˆ

tailcall may not be invoked from within an uplevel into a procedure, or inside a catch inside 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 πŸ’–βœ¨πŸ§š