foldr
The function
foldr :: (a -> b -> b) -> b -> t a -> b
is exactly the same as foldr
for lists, only the argument list of type [a]
has been replaced with a container of type t
storing a bunch of a
s. foldr
traverses the container from right to left and accumulates the elements in the
container using the provided accumulator function.
For lists:
GHCi
>>> foldr (+) 0 [1..10]
55
For Maybe:
GHCi
>>> foldr (+) 0 Nothing
0
>>> foldr (+) 0 (Just 5)
5
For trees:
GHCi
>>> tree = Node Empty 5 (Node (Node Empty 3 Empty) 1 (Node Empty 2 Empty))
>>> foldr (+) 0 tree
11
Since addition is associative, the results in these examples are exactly the
same as when using foldl
in the previous subsection. For non-associative
operations, the results differ:
GHCi
>>> foldr (/) 1 [1,2,4]
2.0
>>> foldl (/) 1 [1,2,4]
0.125