Skip to content

foldl

The function

foldl :: (b -> a -> b) -> b -> t a -> b

is exactly the same as foldl for lists, only the argument list of type [a] has been replaced with a container of type t storing a bunch of as. foldl traverses the container from left to right and accumulates the elements in the container using the provided accumulator function.

For lists:

GHCi
>>> foldl (+) 0 [1..10]
55

Remember, we think of Maybe as a container that stores no element or one element. Thus,

GHCi
>>> foldl (+) 0 Nothing
0
>>> foldl (+) 0 (Just 5)
5

And finally an example that uses a tree. The left-to-right ordering of the nodes in the tree is obtained by recursively visiting the left subtree of each node before the node itself and finally visiting the right subtree.

GHCi
>>> tree = Node Empty 5 (Node (Node Empty 3 Empty) 1 (Node Empty 2 Empty))
>>> foldl (+) 0 tree
11