Using `foldl'` with closure

I find myself writing something like this a lot:

let
  acc = ...
in
  foldl' acc mempty xs

for the simple reason that the accumulating function acc usually doesn’t fit in that same line with foldl'.

What I am missing is, what for and for_ do to traverse and traverse_ and <&> to fmap: a way to write

myVersionOffold mempty xs $ \acc x ->
  ...

Is there some sort of general consensus on how to write those accumulator functions for folds? In my code, they practically never deserve a name, as they are really only used once in the fold.

3 Likes

I use “let” or “where” like you did, too.

The status quo argument order of foldl and foldl’ (and foldr, etc) is to allow me to write like:

f = foldl' acc zzz . sort . map foo

as a pipelining version of

f xs = foldl' acc zzz (sort (map foo xs))

2 Likes

Maybe we need a 3 argument rotation version of flip, say

trip :: (a -> b -> c -> d) -> b -> c -> a -> d
trip f b c a = f a b c

myVersionOffold = trip foldl'

Probably unlikely to catch on :sweat_smile:

I definitely see where you’re coming from. I’ve also often been annoyed about struggling to squeeze a lambda into a single line, then struggling to come up with a good name after I give up and decide to name it.

1 Like

Yes. Sometimes that’s useful. For more complex folds, I give the accumulating function a type signature, which is helpful, too. But often enough, I have folds like C has for-loops: The structure that is folded over is trivial and the folding function does some heavy lifting.

1 Like