haskell / containers

Assorted concrete container types
https://hackage.haskell.org/package/containers
314 stars 177 forks source link

Monadic folds #678

Open sjakobi opened 4 years ago

sjakobi commented 4 years ago

I just needed the following function, which turned out a bit trickier than I had expected:

foldlWithKeyM :: (Ord k, Monad m) => (k -> b -> a -> m b) -> b -> Map k a -> m b
foldlWithKeyM f z0 m = foldrWithKey f' return m z0
  where f' k x g z = f k z x >>= g

Maybe it should be included in containers?

sjakobi commented 4 years ago

I actually ended up simply using foldlM on the toList pairs, to get rid of the somewhat obscure definition above.

I didn't compare the performance though.

treeowl commented 4 years ago

I'm not opposed, but you should propose it on the libraries list. If we do the left folds, we should do the right folds too. You should remove the redundant Ord constraint.

sjakobi commented 4 years ago

I'm unlikely to make a proposal, as foldlM on the toList pairs seems good enough for me.

If a proper definition in containers turns out to offer better performance, I would certainly support a proposal though!