Fold and Reduce
Medium
+3 pts
🎯 Python has several ways to reduce a collection to a single value:
from functools import reduce
sum([1, 2, 3, 4]) # 10
reduce(lambda acc, s: acc + s, ["a", "b"], "") # "ab"
max([3, 1, 4, 1, 5]) # 5
Rust has the same concepts, but with an important distinction between fold (always has an initial value) and reduce (uses the first element). That distinction matters because Rust handles empty collections differently.
.fold(init, f) — accumulate with an initial value
.fold() is Python's reduce with an explicit starting value. It takes an initial accumulator and a closure that combines the accumulator with each element:
Login to see the full exercise.
Topics