Does anyone else use `flip <$> foldr` way more than `foldr` or `foldl`?

Something that always struck me as awkward with foldl and foldr is the b -> f a -> b part of the type signature. So many other useful functions prefer an a -> b -> b style of signature, like everything operating on Maps, Maybes, ‘modify’ style higher order functions, etc.

I defined in one of my catch-all utility modules the following (the name is not very creative)

foldry :: forall f a b. Foldable f => (a -> b -> b) -> f a -> b -> b
foldry = flip <$> foldr

I find that signature reliably more useful and succinct to use. It composes easier, and it’s also good for nested folds.

I was wondering, has anyone else stumbled upon this pattern as well? Or perhaps there is already an knockoff foldr like this published somewhere? I use purescript in relative isolation so I’m curious what others have found.

There’s actually a reason for this. foldl and foldr change whether you start the accumulation function at the “beginning” or “end” of the type (i.e. this is easier to understand when the type is List or Array).

For example, see the visualizations of these functions:

Also, foldr is not always stack-safe. This is most obvious when you use List as the underlying type.

1 Like

I always assumed the b came before the f a so that it was easier to create partially applied functions, e.g. sum = foldl (+) zero.

2 Likes