fold()
February 20, 2022
I think I finally get fold(). In Rust at least, this is a method on an iterator. Its form is:
.fold;
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.