Theory
Folds reduce a list to a single value by combining elements with a binary operator.
| name | type | accumulation order |
|---|---|---|
foldr | rightโassociative | |
foldl | leftโassociative / tailโrecursive |
foldr op z [] = z
foldr op z (x:xs) = x `op` foldr op z xs
foldl op z [] = z
foldl op z (x:xs) = foldl op (z `op` x) xsUse Cases
foldrworks on infinite lists (lazy, needs only whatopdemands).foldl'(strict version) is memoryโfriendly for large finite lists.
Implementation
sumR = foldr (+) 0
sumL = foldl' (+) 0
reverse = foldl (flip (:)) []