liveBook · Manning

Corecursive function

As explained in Functional Programming in Scala, Second Edition

Corecursion is a data-producing form of recursion whose continuation is justified by the ability to generate each next result productively.

A corecursive function produces data rather than consuming it. It may continue indefinitely when each next result can be generated productively—that is, more output becomes available in finite time. section 5.4 section 5.6

Corecursion differs from ordinary recursion in how continuation is justified:

  • Recursive functions consume data and ordinarily recurse on smaller inputs until they terminate. section 5.4
  • Corecursive functions produce data and need not terminate when they remain productive. section 5.4
  • LazyList makes infinite results usable because computation can generate only the demanded portion. section 5.6

Generating a lazy sequence with unfold

def unfold[A, S](state: S)(f: S => Option[(A, S)]): LazyList[A]\n\nThe state records what generation needs next. Each successful result supplies one output value and a new state; Option can signal that generation should stop. The function is productive when f terminates, because one more application produces the next LazyList element. section 5.4

def unfold[A, S](state: S)(f: S => Option[(A, S)]): LazyList[A]

Use the unfold signature to trace the relationship among the seed state, generated value, next state, and optional termination. section 5.4

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines productivity and unfold, then applies the pattern to sequence generators and LazyList operations.
Examples
Uses ones, continually, integer streams, Fibonacci numbers, unfold, and LazyList transformations as construction exercises.
What it assumes
Assumes LazyList and laziness, while establishing productivity through concrete sequence-generation problems.
What you can do after
Build it from scratch by implementing unfold and expressing common infinite or finite LazyList generators through it.
How it connects
Connects recursion, LazyList, laziness, unfold, productivity, and Option-based termination.

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.