haskell - 如何实现 mapAccumM?

标签 haskell

我希望 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

如果没有 State monad,如何做到这一点?

最佳答案

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))))

关于haskell - 如何实现 mapAccumM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11652809/

相关文章:

c++ - 以编程方式在 .doc 中搜索 + 替换

haskell - 函数类似于 "when"但返回一个值?

haskell - 将递归保护更改为高阶函数

haskell - 如何使用数据类型包含函数

function - Haskell 模式匹配在负数上失败

haskell - 没有 Cont Monad 的继续传递风格的评估

haskell - Haskell相互递归的澄清

Haskell IO(字符串)和字符串

xml - haskell xml使用HXT库更新文本

c - Haskell FFI - 如何处理接受或返回结构而不是指向结构的指针的 C 函数?