Skip to content
← Index | Lesson 3 of 5

fold and reduce

Iter.fold to accumulate

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) // 120

Goal: 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

Search Zolo

9 results

enespt-br