typestar

fold and reduce in Rust

Folding an iterator into a single accumulated value.

fn main() {
    let nums = vec![1, 2, 3, 4, 5];

    let product = nums.iter().fold(1, |acc, &n| acc * n);
    let sum_sq: i32 = nums.iter().map(|&n| n * n).sum();
    let first_two: Vec<_> = nums.iter().take(2).collect();
    let any_big = nums.iter().any(|&n| n > 4);
    println!("{product} {sum_sq} {} {any_big}", first_two.len());
}

How it works

  1. fold threads an accumulator through the items.
  2. map(...).sum() is a common specialized fold.
  3. take and any are more iterator finishers.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
313
Tokens
128
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 2 of 3 in Closures & folding, step 7 of 14 in Iterators & closures.

← Previous Next →