foldl
and foldr
are two functions which make people confused easily. Check the types of them:
foldl :: (b -> a -> b) -> b -> [a] -> b
foldr :: (a -> b -> b) -> b -> [a] -> b
The common characteristic of them is the result type is the same as accumulator: b
. A memo to differentiate them is for foldl
: it will traverse the elements from the left of list, and the accumulator also works as the left operand of the binary operator: (b -> a -> b)
. But for foldr
, it goes to the opposite side: it will iterate the elements from the right of list, and the accumulator also works as the right operand of the binary operator: (a -> b -> b)
.
The other important thing is foldr
can operate on infinite list whereas foldl
not.