Tail Calls and Frame Reuse

Identify when no work remains after a call and use that condition to explain constant stack usage for a tail-recursive loop.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. A tail call returns its callee’s answer directly
  2. Reuse the continuation when the calling contract permits it

A tail call returns its callee’s answer directly

In a function returning \(1+f(n-1)\), the caller still has to add one after the recursive result arrives. In an accumulator version returning \(f(n-1,a+1)\), there is no pending arithmetic after the call. That recursive call is in tail position. Position depends on control structure: a selected branch can be in tail position even though the branch condition is evaluated first.

Reuse the continuation when the calling contract permits it

The tail caller can release or reuse its activation and transfer control using the same return continuation. With guaranteed proper tail calls, repeated accumulator steps use bounded stack space, though they can still allocate other objects. Pending cleanup or an incompatible call convention may constrain implementation choices. Stack frames describe the records otherwise accumulated. Continuation-passing style exposes the preserved return continuation as an explicit parameter.[1][2]

References

  1. Shriram Krishnamurthi, Programming Languages: Application and Interpretation ↩
  2. Robert Nystrom, Crafting Interpreters ↩