= Solution
Feed each returned output back as the next input to the same channel <software object>:
``
class RepeatedChannel(inner: Channel, times: Int) extends Channel {
require(times > 0)
override def apply(n: Int): Int = {
var value = n
var completed = 0
while (completed < times) {
value = inner(value)
completed += 1
}
value
}
}
``
The <loop invariant> says that `value` and the component's current state are exactly those after `completed` successive applications starting from this invocation's input and the entry state. The <loop variant> is `times - completed`. On exit the specified number of applications has occurred; the component is not reset or replaced between them.
For input one and a freshly created sum channel, the successive outputs are
$$
1,\ 2,\ 3,\ 5,\ 8,\ 13,\ 21,\ 34,\ 55,\ \boxed{89}.
$$
Initially the component's previous input is zero. The first output is one; on each later call its previous-input state is the input used on the preceding call. Consequently outputs follow the <Fibonacci recurrence> with initial outputs one and two. The answer is \b[89], rather than the result of repeatedly supplying the unchanged external input or recreating the component at every iteration. The component retains its final state for later wrapper calls.
Back to article page