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}");
}
  1. 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

  1. nums starts as [2, 4, 6].
  2. fold starts with acc = 1.
  3. The first step multiplies 1 * 2 to get 2.
  4. The next steps multiply by 4, then by 6.
  5. The final product is 48, so the program prints 48. | 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.