liveBook · Manning

TailRec

As explained in Functional Programming in Scala, Second Edition

TailRec is a book-defined data type that represents recursive control flow as an explicitly interpreted sequence of suspended computations.

TailRec represents recursive control flow as a value built from completed results, suspended computations, and FlatMap composition. A separate run interpreter evaluates that structure, preserving predictable stack usage while keeping computation construction separate from execution. section 13.3.2 section 13.4

TailRec is structured around three cases:

  • Return stores a completed value. section 13.3.2
  • Suspend stores a Function0 whose result is requested during interpretation. section 13.3.2
  • FlatMap sequences a TailRec computation with a continuation; reassociating nested FlatMap values lets run proceed tail-recursively. section 13.3.2
  • The tradeoff is additional overhead and opacity: TailRec avoids stack overflow but does not describe effect kinds, concurrency, or nonblocking I/O. section 13.3.2 section 13.4

Composing many functions

A deeply composed chain of ordinary Int => Int functions can raise StackOverflowError. Changing the return type to TailRec[Int], composing with flatMap, suspending each function call, and finishing with run produces the same results while using predictable stack space. The standard library supplies the corresponding done, tailcall, and result operations. section 13.3.2

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines constructors, combinators, interpretation, stack behavior, and limitations, then connects TailRec to Free.
Examples
Demonstrates a 100,000-function composition failure and a 10,000-function TailRec composition that returns expected values.
What it assumes
Assumes function composition and flatMap, while demonstrating trampolining from ordinary function calls.
What you can do after
Apply TailRec by rewriting function returns, suspending calls, composing with flatMap, and interpreting with run or result.
How it connects
Connects TailRec to trampolining, monads, function composition, asynchronous computation, and Free.

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.