Why foldl and foldr Are Not About Left and Right

Differences Between `Foldl` and `Foldr`

Why foldl and foldr Are Not About Left and Right

Alexis King's classic explanation clarifies that foldl and foldr both traverse lists left to right; the difference is associativity. In lazy languages, foldl builds huge thunks and should be replaced by foldl', while foldr can stream and even handle infinite lists when the reducing function is lazy in its second argument. The rule: use foldl' for strict accumulators, foldr for lazy ones, and never foldl or foldr'.

In both expressions, the elements of the list appear in the expression in the same order—from left to right—but the grouping changes.
  1. s-zeng

    A neat fact about foldr on lists, unlike foldl, is that it actually passes control flow entirely to the accumulating function on each fold step. That means you can use foldr to implement arbitrary traversals of lists, including foldl' or list traversals that exit early. See https://github.com/quchen/articles/blob/master/useful_techni...

  2. layer8

    > Both foldl and foldr traverse the structure in the same order, which in the case of lists means left to right.

    This characterization is debatable, unless one is assuming single-linked lists, which by definition can only be traversed from left to right (even moreso in a lazy language where the list may have indefinite length). When implemented in a strict language on an array or a double-linked list, the traversal order will be right-to-left for foldr.

    A more accurate statement would be that in Haskell, lists can only be traversed from left to right, and therefore the implementations of both foldl and foldr in Haskell are necessarily based on that.

  3. mbauman

    To a CS person, "ordering" is about the arrangement of a list. But pretty much everyone else will think about a *temporal* order of operations. And in that case it is indeed "starting" from the right or left.

    It just gets confusing when you're dealing with lots of deferred/lazy operations.

  4. kccqzy

    I noticed that AI likes to overuse foldl' and foldr (especially foldr) including analogous versions on Maps, even when there are simpler and more straightforward ways to achieve the same thing.

    When AI writes foldr with a complicated accumulation function, I’d prompt AI to define a custom monoidal structure and then use foldMap. Then the reader doesn’t have to think about the asymmetric accumulation function and instead think about the mapping operation and the associative combine function separately. Factoring out the two jobs of the accumulation function is a great trick to improve readability: excellent tradeoff if the human is mostly reading the code.

  5. lukebitts

    This was a very interesting read. Makes me want to try learning Haskell again after failing miserably a few years ago

More from this day

2026-10-05