Iterators
Fold
Reducing to One Value
fold carries an accumulator across the sequence, combining each item into a single result.
Program
Play the program to multiply every number into a running product.
fold_sum.rs
Replay: real traced execution (multi-file project)
fn main() {
let nums = vec![2, 4, 6];
let product = nums.iter().fold(1, |acc, &n| acc * n);
println!("{product}");
}
nums ← [2, 4, 6], product ← 48
1fn main() {2 let num→ [2, 4, 6]s = vec![2, 4, 6];3 let produc→ 48t = nums.iter().fold(1, |acc, &n| acc * n);4 println!("{product}");5}output48
Follow the Fold
numsstarts as[2, 4, 6].foldstarts withacc = 1.- The first step multiplies
1 * 2to get2. - The next steps multiply by
4, then by6. - The final product is
48, so the program prints48. | item | calculation | accumulator after | | --- | --- | --- | | 2 |1 * 2| 2 | | 4 |2 * 4| 8 | | 6 |8 * 6| 48 |
fold
`fold(init, f)` starts from `init` and folds each item in.
accumulator
`acc` carries state between steps.
reduce
The whole sequence collapses to one value.
Exercise: fold_sum.rs
Reproduce the output 48, then trace each accumulator value from 1 to 2 to 8 to 48.