Theory

Folds reduce a list to a single value by combining elements with a binary operator.

nametypeaccumulation order
foldrrightโ€‘associative
foldlleftโ€‘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) xs

Use Cases

  • foldr works on infinite lists (lazy, needs only what op demands).
  • foldl' (strict version) is memoryโ€‘friendly for large finite lists.

Implementation

sumR  = foldr (+) 0
sumL  = foldl' (+) 0
 
reverse = foldl (flip (:)) []