我正在寻找一种在IO monad中使用mapAccumL的方法 - 类似于mapM的模拟,即使用这种类型的签名:
mapAccumLM :: (Monad m) => (a -> b -> m(a, c)) -> a -> [b] -> m(a, [c])
这么简单吗?
答案 0 :(得分:6)
这基本上是mapM
上的StateT a IO
:
mapAccumLM f a xs = runStateT (mapM (StateT . f) xs) a
答案 1 :(得分:1)
与mapAccumL
非常相似:
mapAccumLM :: Monad m => (a -> b -> m(a, c)) -> a -> [b] -> m(a, [c])
mapAccumLM _ a [] = return (a, [])
mapAccumLM f a (x:xs) = do
(a', c) <- f a x
(a'', cs) <- mapAccumLM f a' xs
return (a'', c:cs)