## fold function

In functional programming, fold or "reduce" is a kind of higher-order function that takes as arguments a function, an initial "accumulator" value and a data structure (often a list).

In Haskell, the two flavours of fold for lists, called foldl and foldr are defined like this:

foldl :: (a -> b -> a) -> a -> [b] -> a foldl f z [] = z foldl f z (x:xs) = foldl f (f z x) xs

foldr :: (a -> b -> b) -> b -> [a] -> b foldr f z [] = z foldr f z (x:xs) = f x (foldr f z xs)

In both cases, if the input list is empty, the result is the value of the accumulator, z.

If not, foldl takes the head of the list, x, and returns the result of recursing on the tail of the list using (f z x) as the new z. foldr returns (f x q) where q is the result of recursing on the tail.

The "l" and "r" in the names refer to the associativity of the application of f. Thus if f = (+) (the binary plus operator used as a function of two arguments), we have:

foldl (+) 0 [1, 2, 3] = (((0 + 1) + 2) + 3

(applying + left associatively) and

foldr (+) 0 [1, 2, 3] = 0 + (1 + (2 + 3))

(applying + right associatively). For +, this makes no difference but for an non-commutative operator it would.