In Functional Programming, a fold is a Higher-Order Function that processes a Data Structure, typically an Array, into a single cumulative result.
All folds have an accumulator (aka seed), which is the initial value that the operation starts with. We then go through the data structure performing some processing that effects the accumulator.
Fold Trinity
There are 3 kinds of folds.
- map
- Transform every element. The structure is preserved, only the values change
- An empty list is the accumulator
- e.g. apply a square function to a list of errors, as part of performing a regression
- filter
- Keep only elements that satisfy a condition
- The data structure is the accumulator
- e.g. give only the even values of this list
- reduce
- Collapse all elements into a single value using a binary operation
- The first element as the accumulator
- e.g. give the sum of a list