Folding an infinite list

One big difference is that right folds work on infinite lists, whereas left ones don’t! To put it plainly, if you take an infinite list at some point and you fold it up from the right, you’ll eventually reach the beginning of the list. However, if you take an infinite list at a point and you try to fold it up from the left, you’ll never reach an end!

Learn You a Haskell for Great Good!

Note that the key difference between a left and a right fold is not the order in which the list is traversed, which is always from left to right, but rather how the resulting function applications are nested.

  • With foldr, they are nested on “the inside”

    foldr f y (x:xs) = f x (foldr f y xs)

    Here, the first iteration will result in the outermost application of f. Thus, f has the opportunity to be lazy so that the second argument is either not always evaluated, or it can produce some part of a data structure without forcing its second argument.

  • With foldl, they are nested on “the outside”

    foldl f y (x:xs) = foldl f (f x y) xs

    Here, we can’t evaluate anything until we have reached the outermost application of f, which we will never reach in the case of an infinite list, regardless of whether f is strict or not.

— edited Oct 24 ’11 at 12:21, answered Sep 13 ’11 at 5:17, hammar

— Stack Overflow

2015.08.23 Sunday by ACHK