84

I wanted to test foldl vs foldr. From what I've seen you should use foldl over foldr when ever you can due to tail reccursion optimization.

This makes sense. However, after running this test I am confused:

foldr (takes 0.057s when using time command):

a::a -> [a] -> [a]
a x = ([x] ++ )

main = putStrLn(show ( sum (foldr a [] [0.. 100000])))

foldl (takes 0.089s when using time command):

b::[b] -> b -> [b]
b xs = ( ++ xs). (\y->[y])

main = putStrLn(show ( sum (foldl b [] [0.. 100000])))

It's clear that this example is trivial, but I am confused as to why foldr is beating foldl. Shouldn't this be a clear case where foldl wins?

AndrewC
  • 32,300
  • 7
  • 79
  • 115
Ori
  • 4,961
  • 10
  • 40
  • 39

7 Answers7

116

Welcome to the world of lazy evaluation.

When you think about it in terms of strict evaluation, foldl looks "good" and foldr looks "bad" because foldl is tail recursive, but foldr would have to build a tower in the stack so it can process the last item first.

However, lazy evaluation turns the tables. Take, for example, the definition of the map function:

map :: (a -> b) -> [a] -> [b]
map _ []     = []
map f (x:xs) = f x : map f xs

This wouldn't be too good if Haskell used strict evaluation, since it would have to compute the tail first, then prepend the item (for all items in the list). The only way to do it efficiently would be to build the elements in reverse, it seems.

However, thanks to Haskell's lazy evaluation, this map function is actually efficient. Lists in Haskell can be thought of as generators, and this map function generates its first item by applying f to the first item of the input list. When it needs a second item, it just does the same thing again (without using extra space).

It turns out that map can be described in terms of foldr:

map f xs = foldr (\x ys -> f x : ys) [] xs

It's hard to tell by looking at it, but lazy evaluation kicks in because foldr can give f its first argument right away:

foldr f z []     = z
foldr f z (x:xs) = f x (foldr f z xs)

Because the f defined by map can return the first item of the result list using solely the first parameter, the fold can operate lazily in constant space.

Now, lazy evaluation does bite back. For instance, try running sum [1..1000000]. It yields a stack overflow. Why should it? It should just evaluate from left to right, right?

Let's look at how Haskell evaluates it:

foldl f z []     = z
foldl f z (x:xs) = foldl f (f z x) xs

sum = foldl (+) 0

sum [1..1000000] = foldl (+) 0 [1..1000000]
                 = foldl (+) ((+) 0 1) [2..1000000]
                 = foldl (+) ((+) ((+) 0 1) 2) [3..1000000]
                 = foldl (+) ((+) ((+) ((+) 0 1) 2) 3) [4..1000000]
                   ...
                 = (+) ((+) ((+) (...) 999999) 1000000)

Haskell is too lazy to perform the additions as it goes. Instead, it ends up with a tower of unevaluated thunks that have to be forced to get a number. The stack overflow occurs during this evaluation, since it has to recurse deeply to evaluate all the thunks.

Fortunately, there is a special function in Data.List called foldl' that operates strictly. foldl' (+) 0 [1..1000000] will not stack overflow. (Note: I tried replacing foldl with foldl' in your test, but it actually made it run slower.)

Joey Adams
  • 41,996
  • 18
  • 86
  • 115
  • Good to note that `sum` will usually work, due to strictness analysis. – singpolyma Oct 22 '12 at 18:46
  • 3
    *"The only way to do it efficiently would be to build the elements in reverse, it seems."* not if your compiler performs [tail recursion modulo cons](http://en.wikipedia.org/wiki/Tail_call#Tail_recursion_modulo_cons) optimization. :) Then it works just like guarded recursion with a strict data constructor. – Will Ness Oct 24 '12 at 19:04
  • 1
    @WillNess: Does GHC not have that optimization? – Elliot Cameron Feb 14 '14 at 13:40
  • 1
    @3noch not as far as I know. but it mostly just doesn't apply, since Haskell is lazy and, as I hinted above, lazy guarded recursion is equivalent to it. and, correction: it should read *lazy data constructor*, I think: in `map f (x:xs) = f x : map f xs`, the recursion of `map` is *guarded* by the *lazy* list constructor `:`. If `:` were strict, there wouldn't be any guarding, just plain recursion. I think a comma is missing there: "... then it works just like guarded recursion, (even if) with a strict data constructor" - *if* the TRMCO is present. – Will Ness Feb 14 '14 at 16:59
  • I have a doubt .. You said in last foldl example : "Haskell is too lazy to go ahead and perform the additions, so this yields a stack overflow"... I think foldl takes lots of memory because of new and new thunks and so run out of memory, rather than running out of stack memory.. that is why.. foldr crashes instantly as stack memory is smaller than total system memory.. – Ashish Negi Jul 02 '15 at 15:04
  • @AshishNegi: foldl does use heap memory to allocate the thunks, but when it's time to evaluate all those thunks, it uses a lot of stack, which causes a stack overflow. – Joey Adams Jul 02 '15 at 17:30
  • @JoeyAdams Is it always that evaluation of thunks would happen on stack or it depends upon the function `f` ? like in case of `(:)` would it take the stack ? I mean when function require immediately only first argument, would it be using stack or not ? Or are their special cases.. sorry, for qa.. but I wanted to understand it really. – Ashish Negi Jul 07 '15 at 14:10
  • @JoeyAdams What i meant that does it happen on stack recursively ? obviously, functions would evaluate on stack.. but only when we are recursing too much, then we get stack overflow.. – Ashish Negi Jul 08 '15 at 09:13
  • @AshishNegi: It depends on whether the function is strict in its arguments. `(:)` is not strict; when you force `(:) x xs`, it just returns a cons with the two lazy thunks you gave it. But `(+)` is strict in both of its arguments; when you force `(+) a b`, it has to first force `a` and `b`, then add the resulting numbers together. – Joey Adams Jul 08 '15 at 23:01
  • @JoeyAdams That makes me wonder if I use a customized list structure as follows `data MyList a = EmptyList | MakeList (MyList a) a`, in a opposite fashion of haskell's built-in list, our understanding of `foldr` and `foldl` would be the other way around? – dhu Feb 23 '18 at 18:18
27

Upon looking at this problem again, I think all current explanations are somewhat insufficient so I've written a longer explanation.

The difference is in how foldl and foldr apply their reduction function. Looking at the foldr case, we can expand it as

foldr (\x -> [x] ++ ) [] [0..10000]
[0] ++ foldr a [] [1..10000]
[0] ++ ([1] ++ foldr a [] [2..10000])
...

This list is processed by sum, which consumes it as follows:

sum = foldl' (+) 0
foldl' (+) 0 ([0] ++ ([1] ++ ... ++ [10000]))
foldl' (+) 0 (0 : [1] ++ ... ++ [10000])     -- get head of list from '++' definition
foldl' (+) 0 ([1] ++ [2] ++ ... ++ [10000])  -- add accumulator and head of list
foldl' (+) 0 (1 : [2] ++ ... ++ [10000])
foldl' (+) 1 ([2] ++ ... ++ [10000])
...

I've left out the details of the list concatenation, but this is how the reduction proceeds. The important part is that everything gets processed in order to minimize list traversals. The foldr only traverses the list once, the concatenations don't require continuous list traversals, and sum finally consumes the list in one pass. Critically, the head of the list is available from foldr immediately to sum, so sum can begin working immediately and values can be gc'd as they are generated. With fusion frameworks such as vector, even the intermediate lists will likely be fused away.

Contrast this to the foldl function:

b xs = ( ++xs) . (\y->[y])
foldl b [] [0..10000]
foldl b ( [0] ++ [] ) [1..10000]
foldl b ( [1] ++ ([0] ++ []) ) [2..10000]
foldl b ( [2] ++ ([1] ++ ([0] ++ [])) ) [3..10000]
...

Note that now the head of the list isn't available until foldl has finished. This means that the entire list must be constructed in memory before sum can begin to work. This is much less efficient overall. Running the two versions with +RTS -s shows miserable garbage collection performance from the foldl version.

This is also a case where foldl' will not help. The added strictness of foldl' doesn't change the way the intermediate list is created. The head of the list remains unavailable until foldl' has finished, so the result will still be slower than with foldr.

I use the following rule to determine the best choice of fold

  • For folds that are a reduction, use foldl' (e.g. this will be the only/final traversal)
  • Otherwise use foldr.
  • Don't use foldl.

In most cases foldr is the best fold function because the traversal direction is optimal for lazy evaluation of lists. It's also the only one capable of processing infinite lists. The extra strictness of foldl' can make it faster in some cases, but this is dependent on how you'll use that structure and how lazy it is.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
John L
  • 27,937
  • 4
  • 73
  • 88
  • Unfortunately, `sum` uses foldl, not foldl' (unless they fixed that recently). – Joey Adams Aug 07 '10 at 17:58
  • Wishful thinking on my part. The argument still stands; you just need to replace the accumulator with a giant thunk. – John L Aug 09 '10 at 15:45
  • 1
    `foldl1' (+) [1..100000000]` performs near-instantaneously, whereas all the other folds take a few seconds or result in a stack overflow. – Mateen Ulhaq Jan 15 '19 at 11:34
10

I don't think anyone's actually said the real answer on this one yet, unless I'm missing something (which may well be true and welcomed with downvotes).

I think the biggest different in this case is that foldr builds the list like this:

[0] ++ ([1] ++ ([2] ++ (... ++ [1000000])))

Whereas foldl builds the list like this:

((([0] ++ [1]) ++ [2]) ++ ... ) ++ [999888]) ++ [999999]) ++ [1000000]

The difference in subtle, but notice that in the foldr version ++ always has only one list element as its left argument. With the foldl version, there are up to 999999 elements in ++'s left argument (on average around 500000), but only one element in the right argument.

However, ++ takes time proportional to the size of the left argument, as it has to look though the entire left argument list to the end and then repoint that last element to the first element of the right argument (at best, perhaps it actually needs to do a copy). The right argument list is unchanged, so it doesn't matter how big it is.

That's why the foldl version is much slower. It's got nothing to do with laziness in my opinion.

Will Ness
  • 70,110
  • 9
  • 98
  • 181
Clinton
  • 22,361
  • 15
  • 67
  • 163
  • foldr is taking less time for OP. – Ashish Negi Jul 02 '15 at 14:41
  • @Clinton It makes sense. But does your answer only explains the specific example of OP or the general difference between `foldl` and `foldr`? To me OP picked up a bad example to begin with because the two folding functions are drastically different. – dhu Feb 23 '18 at 17:41
8

The problem is that tail recursion optimization is a memory optimization, not a execution time optimization!

Tail recursion optimization avoids the need to remember values for each recursive call.

So, foldl is in fact "good" and foldr is "bad".

For example, considering the definitions of foldr and foldl:

foldl f z [] = z
foldl f z (x:xs) = foldl f (z `f` x) xs

foldr f z [] = z
foldr f z (x:xs) = x `f` (foldr f z xs)

That's how the expression "foldl (+) 0 [1,2,3]" is evaluated:

foldl (+) 0 [1, 2, 3]
foldl (+) (0+1) [2, 3]
foldl (+) ((0+1)+2) [3]
foldl (+) (((0+1)+2)+3) [ ]
(((0+1)+2)+3)
((1+2)+3)
(3+3)
6

Note that foldl doesn't remember the values 0, 1, 2..., but pass the whole expression (((0+1)+2)+3) as argument lazily and don't evaluates it until the last evaluation of foldl, where it reaches the base case and returns the value passed as the second parameter (z) wich isn't evaluated yet.

On the other hand, that's how foldr works:

foldr (+) 0 [1, 2, 3]
1 + (foldr (+) 0 [2, 3])
1 + (2 + (foldr (+) 0 [3]))
1 + (2 + (3 + (foldr (+) 0 [])))
1 + (2 + (3 + 0)))
1 + (2 + 3)
1 + 5
6

The important difference here is that where foldl evaluates the whole expression in the last call, avoiding the need to come back to reach remembered values, foldr no. foldr remember one integer for each call and performs a addition in each call.

Is important to bear in mind that foldr and foldl are not always equivalents. For instance, try to compute this expressions in hugs:

foldr (&&) True (False:(repeat True))

foldl (&&) True (False:(repeat True))

foldr and foldl are equivalent only under certain conditions described here

(sorry for my bad english)

matiascelasco
  • 1,145
  • 2
  • 13
  • 18
2

For a, the [0.. 100000] list needs to be expanded right away so that foldr can start with the last element. Then as it folds things together, the intermediate results are

[100000]
[99999, 100000]
[99998, 99999, 100000]
...
[0.. 100000] -- i.e., the original list

Because nobody is allowed to change this list value (Haskell is a pure functional language), the compiler is free to reuse the value. The intermediate values, like [99999, 100000] can even be simply pointers into the expanded [0.. 100000] list instead of separate lists.

For b, look at the intermediate values:

[0]
[0, 1]
[0, 1, 2]
...
[0, 1, ..., 99999]
[0.. 100000]

Each of those intermediate lists can't be reused, because if you change the end of the list then you've changed any other values that point to it. So you're creating a bunch of extra lists that take time to build in memory. So in this case you spend a lot more time allocating and filling in these lists that are intermediate values.

Since you're just making a copy of the list, a runs faster because it starts by expanding the full list and then just keeps moving a pointer from the back of the list to the front.

Harold L
  • 5,166
  • 28
  • 28
1

Neither foldl nor foldr is tail optimized. It is only foldl'.

But in your case using ++ with foldl' is not good idea because successive evaluation of ++ will cause traversing growing accumulator again and again.

Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73
-3

Well, let me rewrite your functions in a way that difference should be obvious -

a :: a -> [a] -> [a]
a = (:)

b :: [b] -> b -> [b]
b = flip (:)

You see that b is more complex than a. If you want to be precise a needs one reduction step for value to be calculated, but b needs two. That makes the time difference you are measuring, in second example twice as much reductions must be performed.

//edit: But time complexity is the same, so I wouldn't bother about it much.

Martin Jonáš
  • 2,309
  • 15
  • 12
  • 3
    I tried changing it to `a = flip $ flip (:)` and that didn't change the execution time noticeably, so I don't think that flipping the arguments to accommodate foldl is the problem. – Harold L Aug 07 '10 at 08:54