liveBook · Manning

Tail call

As explained in Elixir in Action, Third Edition

A tail call is a function call that is the final operation performed by its caller, allowing the caller's execution frame to be reused.

A tail call is the final operation performed by a function. Elixir, through Erlang's execution model, can replace the caller's stack push with a jump, allowing the callee to reuse the caller's execution frame and consume no additional memory. section 3.4.2

Tail calls are especially useful for recursion. A function that calls itself at the end can continue through arbitrarily large iterations without accumulating stack frames. The usual pattern separates a public function from a private recursive helper carrying an accumulator. section 3.4.2

Tail-recursive list summation

ListHelper.sum/1 starts with an accumulator of zero, while do_sum/2 adds each head to the accumulated value and tail-calls itself with the remaining list. The empty-list clause returns the accumulated sum.

How Elixir in Action, Third Edition covers it

How deep it goes
Defines the final-operation condition, explains jump-based stack reuse, and applies it to recursive summation.
Examples
Uses an endless recursive loop and an accumulator-based ListHelper.sum/1 implementation.
What you can do after
Build it from scratch by converting recursive list processing into an accumulator-based tail-recursive implementation.
How it connects
Connects tail calls to recursion, stack space, execution frames, accumulators, and iteration.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.