= Solution
Give the step function one private previous-value cell, freshly allocated for each independent Fibonacci generator:
``
def fibonacci(): Iter[BigInt] = {
var previous = BigInt(1)
val step: BigInt => BigInt = { current =>
val following = previous + current
previous = current
following
}
new FunIter[BigInt](BigInt(0), step)
}
``
The initial artificial previous value is $F_{-1}=1$, making the first update return one. Thereafter, just before advancing from $F_n$, the captured cell holds $F_{n-1}$; the assignment produces $F_{n+1}$ and retains $F_n$. <Induction> gives \b[$0,1,1,2,3,5,8,\ldots$]. `BigInt` avoids the fixed-width overflow that would prevent `Int` from representing all <Fibonacci numbers>.
Copies made through part (c) share memoized future cells, so interleaving their traversal does not advance this private state twice for the same sequence position. A separate call to `fibonacci()` receives a separate closure. Another valid construction uses a pure step on the pair $(F_n,F_{n+1})$ and projects the first coordinate; the stateful construction above follows the suggested single-current-value approach.
Back to article page