[Haskell-cafe] Decision procedure for foldr/foldl/foldl'?

Yves Parès limestrael at gmail.com
Mon Nov 21 11:48:31 CET 2011

I would say a good practice with folds (and maybe in Haskell in general) is
that either all be strict or all be lazy.

In the expression: foldXX f init list:

Remember that foldr does:
x `f` ( ... the accumulator ... )
and foldl:
(... the accumulator ...) `f` x

The accumulator has to match a non-strict argument of* f*, so that *f* will
be able to return results *even if* the accumulator is not fully evaluated.

More detailed:
if *f* is lazy in its second argument, then use foldr. Everything is lazy,
you build a very small thunk since nothing is evaluated.
In the rare cases where* f *is (also) lazy in its first argument, you can
use foldl.
And of course, if *f* is strict in both its arguments, then use foldl'.
Everything is then strict, you build no thunk.

2011/11/20 David Fox <ddssff at gmail.com>

> Does anyone have a quick way to decide which of the fold functions to
> use in a given situation?  There are times when I would like to find
> out which to use in the quickest way possible, rather than reading a
> long explanation of why each one behaves the way it does.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20111121/a8c4ea45/attachment.htm>

More information about the Haskell-Cafe mailing list