[Haskell-cafe] foldl vs. foldr

Miguel Mitrofanov miguelimo38 at yandex.ru
Tue Sep 18 15:35:39 CEST 2012


Hi Jan!

foldl always traverses the list to the end; in particular, if there is no end, it would hang forever (unless the compiler is smart enough to detect an infinite loop, in which case it can throw an error). On the other hand, if the first argument is lazy enough, foldr would stop before processing the complete list. So, for example

foldr (\_ _ -> ()) () [1..]

would give an answer, while

foldl (\_ _ -> ()) () [1..]

would hang.

In particular, you can reimplement foldl in terms of foldr, like that:

foldl op i ls = foldr (flip op) i (reverse ls)

but if you attempt to do the same with foldr:

foldr op i ls = foldl (flip op) i (reverse ls)

you would end up with a function which is more strict than the real foldr.

18.09.2012, 16:32, "Jan Stolarek" <jan.stolarek at p.lodz.pl>:
> Hi list,
>
> I have yet another question about folds. Reading here and there I encountered statements that
> foldr is more important than foldl, e.g. in this post on the list:
> http://www.haskell.org/pipermail/haskell-cafe/2012-May/101338.html
> I want to know are such statements correct and, if so, why? I am aware that foldl' can in some
> circumstances operate in constant space, while foldr can operate on infinite lists if the folding
> function is lazy in the second parameter. Is there more to this subject? Properties that I
> mentioned are more of technical nature, not theoretical ones. Are there any significant
> theoretical advantages of foldr? I read Bird's and Wadler's "Introduction to functional
> programming" and it seems to me that foldl and foldr have the same properties and in many cases
> are interchangeable.
>
> Greets,
> Janek
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list