Tail Calls and Accumulated State

A tail call is made when its result can become the current function's result without further computation.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Move the pending work
  2. Separate source form from runtime behavior
  3. Move the unfinished operation into an argument
  4. Preserve the update order in an iterative translation

Move the pending work

An ordinary recursive sum may return \(n+f(n-1)\), leaving an addition pending. An accumulator version calls a helper on the smaller input and a new accumulated sum, then returns that call directly. This resembles a loop accumulator written with new arguments each step.

Separate source form from runtime behavior

The tail position allows some runtimes to reuse a frame. It does not by itself guarantee that the language implementation does so. Tail-call elimination explains the runtime conditions that make deep tail recursion practical.[1]

Move the unfinished operation into an argument

A factorial function with arguments \(n\) and \(a\) can preserve the invariant \(a\,n!=N!\), where \(N\) is the original input. The step replaces the pair by \((n-1,an)\). At zero, the accumulator alone holds the answer. See loop accumulators.

State (n, a)      Conserved product
(4, 1)            1 × 24 = 24
(3, 4)            4 × 6  = 24
(2, 12)           12 × 2 = 24
(1, 24)           24 × 1 = 24
(0, 24)           return 24

Preserve the update order in an iterative translation

The next accumulator uses the old \(n\). Decrementing first and then multiplying eventually multiplies by zero. A tail call needs no suspended multiplication, but Python still allocates call frames for normal recursion. An explicit loop can preserve the invariant without relying on tail-call optimization.

References

  1. Jeff Erickson, Algorithms ↩