Iterator Pipelines
Fold Count
Accumulate a Derived Value
fold carries an accumulator through every item that reaches the end of an iterator pipeline.
Program
Play the program to choose whether zero readings should count as included readings.
fold_count.rs
Replay: real traced execution (multi-file project)
fn main() {
let include_zero = false;
let readings = [3, 0, 4];
let count = readings.iter().copied().filter(|value| include_zero || *value != 0).fold(0, |acc, _value| acc + 1);
println!("count={count}");
}
fn main() {
let include_zero = true;
let readings = [3, 0, 4];
let count = readings.iter().copied().filter(|value| include_zero || *value != 0).fold(0, |acc, _value| acc + 1);
println!("count={count}");
}
include_zero ← false, readings ← [3, 0, 4], count ← 2
1fn main() {2 let include_zer→ falseo = false; //@include_zero=false, true3 let reading→ [3, 0, 4]s = [3, 0, 4];4 let coun→ 2t = readings.iter().copied().filter(|value| include_zero || *value != 0).fold(0, |acc, _value| acc + 1);5 println!("count={count}");6}outputcount=2
include_zero ← true, readings ← [3, 0, 4], count ← 3
1fn main() {2 let include_zer→ trueo = true;3 let reading→ [3, 0, 4]s = [3, 0, 4];4 let coun→ 3t = readings.iter().copied().filter(|value| include_zero || *value != 0).fold(0, |acc, _value| acc + 1);5 println!("count={count}");6}outputcount=3
lazy pipeline
The filter and fold stages run only when the final count is requested.
fold
`fold(0, |acc, _value| acc + 1)` increments the accumulator for each included item.
predicate
`include_zero || *value != 0` changes which values reach the fold.