Fold And Reduce Accumulate Sequences

fold carries an initial accumulator of any type while reduce consumes the first element and returns Option, so empty sequences collapse differently.

RustData Integrity

Code

rustsnippet
20 lines
fn main() {
    let latencies = [42u64, 18, 133, 7, 95, 61];

    // fold:带初值,累加器类型可以与元素完全不同(这里换成统计元组)
    let (count, sum) = latencies
        .iter()
        .fold((0usize, 0u64), |(count, sum), &v| (count + 1, sum + v));
    let average = sum as f64 / count as f64;
    println!("count={count} sum={sum} average={average:.1}");

    // reduce:没有初值,直接消费首元素,返回 Option
    let max = latencies.iter().copied().reduce(u64::max);
    let min = latencies.iter().copied().reduce(u64::min);
    println!("max={max:?} min={min:?}");

    // 空输入的分歧:fold 仍产出初值形态,reduce 只能是 None
    let empty: [u64; 0] = [];
    println!("empty fold: {}", empty.iter().fold(0u64, |acc, &v| acc + v));
    println!("empty reduce: {:?}", empty.iter().copied().reduce(u64::max));
}

How the snippet works

Fold And Reduce Accumulate Sequences keeps everything in the function main.

Using it

The demo output is labeled (count=, max=, empty fold:), so every printed line maps back to its originating operation.

Key statements

let max = latencies.iter().copied().reduce(u64::max);
let min = latencies.iter().copied().reduce(u64::min);
.fold((0usize, 0u64), |(count, sum), &v| (count + 1, sum + v));

Interactive Tools for This Topic

FAQ

What does Fold And Reduce Accumulate Sequences print when run?
Execute the whole file; each printed line is prefixed with a label like `count=`, `max=`, `empty fold:`.