unfold generates a LazyList by applying a state-transition function to an initial state. Some produces the next value and state; None ends the list. section 5.4 section 5.6
Generating Fibonacci numbers
Represent the current and next Fibonacci values as state, emit the current value, and advance the pair: unfold((0, 1))(case (current, next) => Some((current, (next, current + next)))). section 5.6
The same state-machine pattern expresses several LazyList operations:
- Generate an increasing sequence by using the next integer as state. section 5.6
- Generate constant or infinite sequences by using Unit as unused state. section 5.6
- Implement map, take, takeWhile, and zipAll by carrying the required list data and counters as state. section 5.4 section 5.6
def unfold[A, S](state: S)(f: S => Option[(A, S)]): LazyList[A]
The signature makes the generator's two roles explicit: S supplies state, while Option[(A, S)] supplies a value, successor state, or termination. section 5.4
unfold is corecursive: it produces data rather than consuming it. Infinite generation is safe when each step remains productive and the transition function terminates. section 5.4 section 5.6
