IT lexicon › Programming › Tail recursion modulo cons

Tail recursion modulo cons

Programming På svenska → Updated: 2026-11-06

An optimization that turns recursion where the only work left after the call is building a data structure into a loop running in constant stack space.

The naive map over lists ends in f x :: map f xs. The call isn't in tail position — the cons cell gets built afterwards — so every element costs a stack frame and a long enough list blows the stack. The trick is to allocate the cell first with a hole where the tail goes, and let the recursive call fill in the hole. Now the call is the last thing that happens and can become a jump.

Daniel Friedman and David Wise described the transformation in 1974, and in Prolog it falls out of logic variables for free. OCaml got it as the opt-in attribute [@tail_mod_cons] in version 4.14 in 2022, after decades of programmers hand-writing a List.rev of an accumulator. Koka has generalised the idea to arbitrary constructor contexts.

← Back to the lexicon