<div dir="ltr"><div dir="ltr">I propose adding a pair of functions to Data.Traversable: mapAccumLM and mapAccumRM with the type '(Traversable t, Monad m) => (a -> b -> m (a,c)) -> a -> t b -> m (a, t c)'. These would behave exactly the same as mapAccumL and mapAccumR, but would allow the addition of monadic effects.<br><br>This would allow the traversal of structures with an accumulator, without resorting to using foldlM or foldrM, both of which require the extra boilerplate of reconstructing the structure after applying the action, which can be somewhat frustrating and error-prone.<br><br>A possible implementation would be to add transformer counterparts to StateL/StateR in Data.Functor.Util: (gist: <a href="https://gist.github.com/TOTBWF/dc6020be28df7b00372ab8e507aa54b7">https://gist.github.com/TOTBWF/dc6020be28df7b00372ab8e507aa54b7</a>)<br><br>    newtype StateLT s m a = StateLT { runStateLT :: s -> m (s,a) }<br><br>    instance (Functor m) => Functor (StateLT s m) where<br>      fmap f (StateLT k) = StateLT $ \s -> fmap (\(s',a) -> (s', f a)) $ k s<br><br>    instance Monad m => Applicative (StateLT s m) where<br>      pure a = StateLT $ \s -> return (s, a)<br>      StateLT kf <*> StateLT kv = StateLT $ \s -> do<br>        (s', f) <- kf s<br>        (s'', v) <- kv s'<br>        return (s'', f v)<br>      liftA2 f (StateLT kx) (StateLT ky) = StateLT $ \s -> do<br>        (s', x) <- kx s<br>        (s'', y) <- ky s'<br>        return (s'', f x y)<br><br>    mapAccumLM :: (Monad m, Traversable t) => (a -> b -> m (a,c)) -> a -> t b -> m (a, t c)<br>    mapAccumLM f s t = runStateLT (traverse (StateLT . flip f) t) s<br><br>    newtype StateRT s m a = StateRT { runStateRT :: s -> m (s,a) }<br><br>    type StateR s = StateRT s Identity<br><br>    instance (Functor m) => Functor (StateRT s m) where<br>      fmap f (StateRT k) = StateRT $ \s -> fmap (\(s',a) -> (s', f a)) $ k s<br><br>    instance Monad m => Applicative (StateRT s m) where<br>      pure a = StateRT $ \s -> return (s, a)<br>      StateRT kf <*> StateRT kv = StateRT $ \s -> do<br>        (s', v) <- kv s<br>        (s'', f) <- kf s'<br>        return (s'', f v)<br>      liftA2 f (StateRT kx) (StateRT ky) = StateRT $ \s -> do<br>        (s', y) <- ky s<br>        (s'', x) <- kx s'<br>        return (s'', f x y)<br><br>    mapAccumRM :: (Monad m, Traversable t) => (a -> b -> m (a,c)) -> a -> t b -> m (a, t c)<br>    mapAccumRM f s t = runStateRT (traverse (StateRT . flip f) t) s<br><br></div></div>