Sub topic 10
Tail Calls and Tail-Call Optimization
This chapter assumes you can write recursive functions with a base case, picture the call stack as a pile of frames, and pass running results through an accumulator parameter. It explains what makes a call a tail call, what tail-call optimization (TCO) does to the stack, and which languages actually perform it.
What Makes a Call a Tail Call
A tail call is a function call that is the very last action of the calling function. When it returns, the caller hands its result straight back and has nothing left to compute. A function is tail recursive when every recursive call it makes is a tail call.
def sum_to(n):
if n == 0:
return 0
return n + sum_to(n - 1) # not a tail call: "+" runs after the call returns
def sum_to_tail(n, acc=0):
if n == 0:
return acc
return sum_to_tail(n - 1, acc + n) # tail call: the result is returned unchanged
print(sum_to(100)) # 5050
print(sum_to_tail(100)) # 5050In sum_to, each frame has to stay alive so it can add n once the inner call finishes. In sum_to_tail, the frame holds nothing the program will need again. The accumulator acc already carries the partial sum forward.
Spotting Tail Position
| Return expression | Tail call? | Why |
|---|---|---|
| `return f(x)` | Yes | Result passed back unchanged |
| `return f(x) + 1` | No | Addition happens afterward |
| `return n * f(n - 1)` | No | Multiplication happens afterward |
| `return f(x) if c else g(x)` | Yes, both | Whichever branch runs is the last action |
| `return f(x)` inside `try` or `with` | No | Exception handling or cleanup must still run |
The last row catches many people. A finally clause, an exception handler, or a context manager's exit step means the caller still has pending work, so its frame cannot be discarded.
What the Optimization Does
A frame whose only remaining job is to return another call's result does no useful work. With TCO, the runtime reuses the current frame for the tail call, or replaces it, instead of pushing a new one. A tail-recursive function then runs in constant stack space, the same as a loop.
Which Languages Do It
| Language | Tail-call behavior |
|---|---|
| Scheme | Required by the language standard |
| Haskell, OCaml, Erlang/Elixir | Reliable in practice; idiomatic looping relies on it |
| Scala, Kotlin | Only for self-recursion marked `@tailrec` / `tailrec`, compiled to a loop |
| C, C++ | Often done by optimizing compilers (e.g. `-O2`), never guaranteed |
| JavaScript | In the ES2015 spec, but only Safari's engine implements it |
| Java, C#, Python | Not performed for ordinary code |
CPython chose not to implement TCO. A major reason is that it would remove frames from tracebacks and make debugging harder. In Python, a tail-recursive function uses the stack exactly like any other recursive function:
import sys
def sum_to_tail(n, acc=0):
if n == 0:
return acc
return sum_to_tail(n - 1, acc + n)
print(sys.getrecursionlimit()) # typically 1000
try:
sum_to_tail(100_000)
except RecursionError as e:
print("RecursionError:", e)Because Python won't optimize tail calls, the dependable fix is to do the frame reuse yourself by rewriting the function as a loop. The next chapter covers how.
Exercises
Exercise
Is the recursive call in return n * factorial(n - 1) a tail call? Explain.
Show answer
No. After factorial(n - 1) returns, the caller still has to multiply the result by n, so its frame must stay on the stack.
Exercise
A Scheme function makes its only recursive call as return helper(n - 1, acc * n), but in a Python port that line sits inside a try block with an except clause. Is the call in tail position in the Python version, and would CPython optimize it either way?
Show answer
It is not in tail position, because the exception handler must stay active until the call returns. CPython would not optimize it even outside the try, because CPython never performs tail-call optimization.
Exercise
You run a tail-recursive function on input 50,000 in Python and get a RecursionError. Would raising the limit with sys.setrecursionlimit be a safe fix? What would be better?
Show answer
It isn't reliably safe. A higher limit can crash the interpreter by exhausting the real C stack. The better fix is to rewrite the tail-recursive function as a loop, which uses constant stack space.