News for hackers. Stuff that matters.
Re:It never makes sense to use foldl on lists in Haskell (2019) by thaumasiotes on Saturday March 21, 2020 @12:10AM (#22644354)
The example of why you might want to use foldr instead of foldl is really poorly chosen. It relies on the idea that you don't want to reduce the list. There is even original emphasis on this assumption:

> foldr can possibly save on work if the reducing function is lazy in its second argument, and the result list is not entirely consumed. In fact, foldr can operate on infinite lists this way, while foldl cannot.

And to support the idea, we look at an implementation of map in terms of foldr. But I assume that if you're programming in Haskell and you want to map a function over a list, you'll use map instead of defining an ad-hoc mapped version of your function with foldr. This would be a great example of why, when we're defining map itself, we use foldr instead of foldl. But I wanted to see an example of why I might want to use foldr instead of foldl, not why I might want to reimplement map from scratch. They couldn't imagine a reduction that produced a scalar instead of another vector?

Of course, if you're reducing the list to a scalar, you lose all the benefits this article wants to claim.

Re:It never makes sense to use foldl on lists in Haskell (2019) by EvilTerran on Saturday March 21, 2020 @05:32AM (#22645483)
> if you're reducing the list to a scalar, you lose all the benefits this article wants to claim.

Not quite - for example, these both benefit from foldr, despite each producing a scalar:

  and, or :: [Bool] -> Bool
  and = foldr (&&) True
  or = foldr (||) False
... as they can both "bail out early" without evaluating the entire list (if they find a False or a True, respectively).

The distinction lies not so much in "are you reducing to a scalar?" as "can your binary operation be productive without evaluating its second parameter?" - or, if you prefer, "is it ever lazy in its second parameter?". If so, then foldr may be appropriate.