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
foldthreads an accumulator through the items.map(...).sum()is a common specialized fold.takeandanyare more iterator finishers.
Keywords and builtins used here
Vecfni32letmain
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.
Step 2 of 3 in Closures & folding, step 7 of 14 in Iterators & closures.