kdwarn

Codeberg Mastodon Feeds

Home > Programming > Blog > fold()

fold()

February 20, 2022

daybook, rust | permalink

I think I finally get fold(). In Rust at least, this is a method on an iterator. Its form is:

(1..=4).fold(1, |acc, x| acc * x);

1..=4 is a range, so this will iterate from 1 to 4.

The 1 immediately following fold( is the initial value. So this could be anything, and will typically come from whatever you're iterating over. The next part - |acc, x| acc + x is the closure that .fold() takes - this consists of two parameters (the "accumulator", acc, and current element of the iteration, x) and the operation of the closure (acc + x). So with each iteration, the operation is performed, and the acc parameter holds the result, which then gets used in the next iteration.

The above example is a factorial, and so multiples every number for 1 to 4 (inclusive) together, resulting in 24.