(This question applies more generally than to Haskell, but that's the language I'll use to state it.)
The distinction between foldl
and foldr
seems to depend on the fact that lists are ordered. That is, foldl
and foldl
collapse a list by applying a function to a starting value and the first or last element, then to the result of the first application and the second or second-to-last element, then the result of the second application to the third or third-to-last element, etc.
But the Data.Set and Data.Map libraries for Haskell define their own versions of foldl
and foldr
. For instance, for maps they are these:
foldr :: (a -> b -> b) -> b -> Map k a -> b
foldl :: (b -> a -> b) -> b -> Map k a -> b -- I've swapped `a` and `b`
-- in the second type signature to clarify the correspondence.
Maps and sets aren't ordered. Should I expect performance differences between the versions of foldl
and foldr
defined for sets and maps, or does foldr f
do exactly the same thing as foldl (flip f)
?
foldl
can run lazily whilefoldr
is strict. Apart from that there are many different use cases. Such asfoldr
ing items into a list could be much more efficient thanfoldl
ing. – Exontake 5 (foldr (:) [] [1..])
terminates. What do you mean by "lazy" and "strict"? – Beograd