foldr and foldl further explanations and examples

Viewed 27085

I've looked at different folds and folding in general as well as a few others and they explain it fairly well.

I'm still having trouble on how a lambda would work in this case.

foldr (\y ys -> ys ++ [y]) [] [1,2,3]

Could someone go through that step-by-step and try to explain that to me?

And also how would foldl work?

6 Answers

My way of remembering this firstly, is through the use of an associative sensitive subtraction operation:

foldl (\a b -> a - b) 1 [2] = -1
foldr (\a b -> a - b) 1 [2] = 1

Then secondly , foldl starts at the leftmost or first element of the list whereas foldr starts at the rightmost or last element of the list. It is not obvious above since the list has only one element.

My mnemonic is this: The left or right describes two things:

  • the placement of the minus (-) symbol
  • the starting element of the list

I tend to remember things with movement, so I imagine and visualize values flying around. This is my internal representation of foldl and foldr.

The diagram below does a few things:

  1. names the arguments of the fold functions in a way that is intuitive (for me),
  2. shows which end each particular fold works from, (foldl from the left, foldr from the right),
  3. color codes the accumulator and current values,
  4. traces the values through the lambda function, mapping them onto the next iteration of the fold.

Mnemonically, I remember the arguments of foldl as being in alphabetical order (\a c ->), and the arguments of foldr to be in reverse alphabetical order (\c a ->). The l means take from the left, the r means take from the right.

A Story of Two Folds

Related