Iterators · 6.3
fold and reduce
All lessons are open — jump whenever you need.
fold accumulates values with a function:
use std::Iter
let nums = [1, 2, 3, 4, 5]
// Sum
let sum = Iter::from(nums).fold(0, |acc, x| acc + x)
print(sum) // 15
// Product
let product = Iter::from(nums).fold(1, |acc, x| acc * x)
print(product) // 120Goal: Use fold to find the largest number in [3, 7, 1, 9, 4, 6]. Result: 9.
lesson-6-3.zolo
Program output
Run the code to see the output