Rust

fold / reduce / scan

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`fold` is the general aggregator: starts from an accumulator, applies a fn to each item. `reduce` uses the first item as the seed. `scan` yields intermediate accumulator values.
Rust
Raw
fn main() {
    let nums = vec![1, 2, 3, 4, 5];

    // fold — explicit initial accumulator
    let sum     = nums.iter().fold(0, |acc, &n| acc + n);
    let product = nums.iter().fold(1, |acc, &n| acc * n);
    println!("sum={sum} product={product}");          // 15 120

    // reduce — Option<T>; None if iterator is empty
    let max = nums.iter().copied().reduce(i32::max);
    println!("{max:?}");                              // Some(5)

    // scan — like fold but yields each intermediate value (running totals)
    let running: Vec<i32> = nums.iter().scan(0, |acc, &n| {
        *acc += n;
        Some(*acc)
    }).collect();
    println!("{running:?}");                          // [1, 3, 6, 10, 15]

    // String concatenation via fold
    let joined: String = ["a", "b", "c"].iter().fold(String::new(), |mut s, p| {
        s.push_str(p);
        s
    });
    println!("{joined}");                             // abc
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.