An important element in functional programming is the fold (also known as reduce ). A fold represents a set of higher-order functions that operate on recursive data structures and take a combining operation as one of the parameters, recombining the results of recursive operations in order to build a return value. In this chapter, you will learn to use fold functions.
fold takes as one of the parameters a function and folds it onto a list.
foldr takes as one of the parameters a function and folds it from right to left onto a list.
foldl takes as one of the parameters a function and folds it from right to left onto a list.
foldr1 is similar to foldr.
foldl1 is similar to foldl.
1 | 2 | 3 | 4 | 5 | 6 |
+ | 1 | + | 2 | + | 3 | + | 4 | + | 5 | + | 6 |
5 | + | 1 | + | 2 | + | 3 | + | 4 | + | 5 | + | 6 |
Indeed, 5+1+2+3+4+5+6=26; therefore, you get the result 26.
Note that you used the left fold, which is the reason why you started folding from the left. Another important note is that the fold functions are not limited to infix functions as the first argument.
For foldr, the two arguments may have different types, resulting in output with the same type as the second argument.
For foldr1, the two arguments must have the same type, resulting in output of the same type as the arguments. Another aspect is that it does not need the starting point (it will choose the rightmost element to start with).
Summary
What fold family functions are and how to work with them
What the opposite of folding is