StateT和forM_

时间:2013-01-07 00:23:06

标签: haskell monads

我怎样才能在forM内部让put在State monad上工作?

loop :: Integer -> StateT World IO ()
loop passes = do
    (scene, b1) <- get
    forM_ [1..passes] $ \pass -> do
        let b2 = foo b1 pass
        -- other stuff --
        put (scene, b2) -- this no longer puts into the StateT monad 

或者是否有更好的方法在一起?

1 个答案:

答案 0 :(得分:1)

我认为它运作正常,例如:

--I don't know what World is so I can't use your example

loop :: StateT Integer IO ()
loop = do
    forM_ [1..10] put
    x <- get
    liftIO $ print x

正在运行evalStateT loop 0打印10,就像我期望的那样。引擎盖下的mapM_就是这样做的:

  1. 实际上是做地图,上面的例子返回一个列表[StateT Integer IO ()]

  2. 执行右侧折叠:foldr (>>) (return ()) listOfMappedValues

  3. 目前尚不清楚你的期望究竟是什么,但是这会让你从mapM_

    进入州内