Iterator::fold
An iterator method that applies a function, producing a single final value.
fold()
takes two arguments: an initial value, and a closure that itself takes two arguments: an 'accumulator', and an element.
The job of the closure is to incrementally produce the final value to return. Starting with the initial value as the accumulator, fold()
will feed the accumulator and the next element from the iterator to the closure. The closure will then return the next value to use as the accumulator.
Once the closure has been applied to every element of the iterator, fold()
returns the accumulator as the final value.
Basic usage:
To see what's going on, we can use dbg!
and watch fold()
progress:
This emits output showing the closure running three times (once for each element) and the acc
incrementing by elem
each time:
fold()
can be combined with other adapters, but is typically the last call in a chain:
A call to fold()
like:
is equivalent to:
reduce()
: like fold()
, but uses the first element in the iterator as the initial value.min
/max
/sum
: useful methods based on fold()
.Several of the other (forward) methods have default implementations in terms of this one, so try to implement this explicitly if it can do something better than the default for
loop implementation.
In particular, try to have this call fold()
on the internal parts from which this iterator is composed.