Every time your program calls a function, the runtime pushes a stack frame — a small block of memory holding the local variables and the return address. Call deeply enough and you exhaust the stack: the dreaded stack overflow.
Recursion is the natural way to express many algorithms, but naive recursion builds a tower of frames proportional to the depth. A function that counts down from a million would need a million frames just sitting there, waiting.
Tail-call optimization (TCO) cuts that tower to one frame. The insight is simple: if the very last thing a function does is call another function — and then return its result unchanged — the caller's frame is useless from that moment on. The compiler can reuse the same frame for the callee, turning the call into a plain jump.
The result: a recursive function in tail position runs in stack space, no matter how deep the recursion goes. First described explicitly by Guy L. Steele Jr. in 1977 and mandated by the Scheme standard, TCO is now guaranteed by languages like Scheme, Erlang, Elixir, and Lua, and present in many modern compilers for Haskell, Scala, and others.
Comments
Loading comments...