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
