3

我想要mapM在传递累加器时可以遍历的东西。我想出了:

import Control.Applicative
import Data.Traversable
import Control.Monad.State

mapAccumM :: (Applicative m, Traversable t, MonadState s m)
             => (s -> a -> m (s, b)) -> s -> t a -> m (t b)
mapAccumM f acc0 xs = put acc0 >> traverse g xs
  where
    g x = do
      oldAcc <- get
      (newAcc, y) <- f oldAcc x
      put newAcc
      return y

没有Statemonad怎么办?

4

1 回答 1

2

roconnor 在#haskell 上为我回答了这个问题

这解决了我的问题,但请注意累加器在元组的第二个元素而不是第一个元素中返回

mapAccumM :: (Monad m, Functor m, Traversable t) => (a -> b -> m (c, a)) -> a -> t b -> m (t c)
mapAccumM f = flip (evalStateT . (Data.Traversable.traverse (StateT . (flip f))))

或者也返回累加器:

mapAccumM' :: (Monad m, Functor m, Traversable t) => (a -> b -> m (c, a)) -> a -> t b -> m (t c, a)
mapAccumM' f = flip (runStateT . (Data.Traversable.traverse (StateT . (flip f))))
于 2012-07-25T15:20:45.283 回答