= Solution
Keep the neighboring <Fibonacci number> in a private <closure>. Before calling the transition with $x=F_n$, let its captured `following` equal $F_{n+1}$.
``
def fibonacci(): Iter[BigInt] = {
var following = BigInt(1)
val step: BigInt => BigInt = (x: BigInt) => {
val result = following
following = x + following
result
}
new FunIter[BigInt](BigInt(0), step)
}
``
The transition returns $F_{n+1}$ and stores $F_n+F_{n+1}=F_{n+2}$, preserving the <paired Fibonacci recurrence>. Initialization gives $F_0=0$ and $F_1=1$, so
$$
\boxed{0,1,1,2,3,5,8,13,21,\ldots.}
$$
Using `BigInt` allows all <Fibonacci numbers> rather than a finite prefix before <integer overflow>. Replacing `BigInt` by `Int` gives the source's suggested machine-<integer> interface with that limitation. With the `FunIter` implementation from part (c), each transition runs once per generated cell, and copied <iterators> can advance independently while sharing the privately owned generator. A simpler alternative uses a <pure function> on pairs, $(a,b)\mapsto(b,a+b)$, and projects the first component; the <closure> above follows the source's suggested single-value approach directly.
Back to article page