typestar

Reduce and fold in Rust

Parallel reduction needs an identity value and an associative operation.

use rayon::prelude::*;

fn main() {
    let values: Vec<i64> = (1..=1_000).collect();

    let sum = values.par_iter().copied().reduce(|| 0, |a, b| a + b);
    println!("{sum}");

    let (count, total) = values
        .par_iter()
        .fold(|| (0u32, 0i64), |(c, t), v| (c + 1, t + v))
        .reduce(|| (0, 0), |a, b| (a.0 + b.0, a.1 + b.1));
    println!("{count} values totalling {total}");

    let longest = ["fig", "banana", "kiwi"]
        .par_iter()
        .max_by_key(|w| w.len());
    println!("{:?}", longest);
}

How it works

  1. reduce combines pairs of results as they finish.
  2. The identity closure supplies a neutral starting value.
  3. fold accumulates per thread before the final reduce.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
463
Tokens
196
Three-star pace
110 tpm

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

Type this snippet

Step 1 of 2 in Reductions, step 4 of 9 in Data parallelism with rayon.

← Previous Next →