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
}
Create a free account and build your private vault. Share publicly whenever you want.