Search code examples
haskellevaluationfold

Default definitions of foldl' and foldr' seem weird


Default definitions of foldl' and foldr' seem weird. They have default definition as:

class Foldable t where
    -- ...
    foldr' f z0 xs = foldl f' id xs z0
      where f' k x z = k $! f x z
    -- ...
    foldl' f z0 xs = foldr f' id xs z0
      where f' x k z = k $! f z x
    -- ...

Why not?:

class Foldable t where
    -- ...
    foldr' f = foldr (\x z -> f x $! z)
    -- ...
    foldl' f = foldl (\z x -> flip f x $! z)
    -- ...

Solution

  • Generally speaking, foldl' is best for things that look kind of like cons-lists and foldr' is best for things that look kind of like snoc-lists. The situations are symmetrical, so let's just look at cons-lists, where foldl' had better be good.

    You've probably read that foldl for cons-lists can lead to space leaks if it's not optimized well enough. Well, that's exactly what will happen here. f' is strict, but none of its results are demanded until the fold has reached the end of the list!

    The default definitions give a little twist, which makes even naive compilation (or interpretation) work properly.