liveBook · Manning

Tail-call optimization

As explained in Functional Programming in Scala, Second Edition

Tail call elimination is a compiler optimization that implements eligible recursive calls without allocating a new call-stack frame for each call.

Tail-call optimization, also called tail-call elimination, implements eligible recursive calls without allocating a new call-stack frame for each iteration. A recursive call is in tail position when the caller returns its result directly and performs no further work. section 2.3.1

Factorial as a loop

A factorial helper carries the remaining number and accumulated result: it returns the accumulator at the base case and calls go(n - 1, n * acc) otherwise. Because that recursive call is the final operation, Scala can compile the recursion like a while loop. Changing it to 1 + go(...) would require work after the call and would no longer be tail-recursive. section 2.3.1

Direct tail recursion handles self-recursive loops, but deeply composed functions can still overflow the stack. Trampolining represents computation as TailRec values and interprets them with a tail-recursive run method, trading some speed for predictable stack usage. section 13.3.2

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines tail position, contrasts eligible and ineligible recursion, traces factorial, and extends the idea to trampolining.
Examples
Demonstrates accumulator-based factorial, execution traces, deeply composed identity functions, and TailRec function composition.
What it assumes
Assumes recursive functions and function composition while developing accumulator-based loops and suspended computation representations.
What you can do after
Evaluate whether recursive calls are in tail position and apply TailRec trampolining when direct composition risks stack overflow.
How it connects
Connects recursion with iteration, stack overflow, trampolining, monads, and function composition.

Also explained in

Compare how 3 books explain tail-call optimization →

Related concepts

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