I had not considered that. I tried it out on a gist (
), and you're definitely right. I don't understand right monadic folds well enough to write those out, but it would probably be worthwhile to both variants of it as well. Here's the code from the gist:
{-# LANGUAGE ScopedTypeVariables #-}
module Folds where
import Control.Applicative
-- Lazy in the monoidal accumulator.
foldlMapM :: forall g b a m. (Foldable g, Monoid b, Applicative m) => (a -> m b) -> g a -> m b
foldlMapM f = foldr f' (pure mempty)
where
f' :: a -> m b -> m b
f' x y = liftA2 mappend (f x) y
-- Strict in the monoidal accumulator. For monads strict
-- in the left argument of bind, this will run in constant
-- space.
foldlMapM' :: forall g b a m. (Foldable g, Monoid b, Monad m) => (a -> m b) -> g a -> m b
foldlMapM' f xs = foldr f' pure xs mempty
where
f' :: a -> (b -> m b) -> b -> m b
f' x k bl = do
br <- f x
let !b = mappend bl br
k b