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
