结合RWST和IO

时间:2018-03-24 12:57:18

标签: haskell monads monad-transformers

我需要在RWS内部执行IO操作,因此我决定将RWST与IO monad结合使用。虽然一切正常,但我无法从外部monad获取日志。

这就是我目前所拥有的:

newtype VM2 a = VM2{
    unwrapVM :: RWST () () () IO a } 
deriving (Functor, Applicative, Monad, MonadIO)

runVmEval :: VM2 a -> IO () 
runVmEval m = do 
                evalRWST (run) () ()
                putStrLn $ "End"

test :: IO () 
test = do
         putStrLn "Start"
         runVmEval $ return ()

run :: RWST () [String] () IO () 
run = do 
        x <- lift getLine
        tell $ [x]
        lift (print x)

这就是我想做的事情:

runVmEval :: VM2 a -> IO ()
runVmEval m = do
    let w = evalRWST (run) () ()
    putStrLn $ snd w
    putStrLn $ "End"

这显然是失败的,因为w是IO ((), [String])

类型

我也尝试了以下内容:

runVmEval :: VM2 a -> IO ()
runVmEval m = do
    let (a,w) = evalRWST (run) () ()
    putStrLn $ "End"
    mapM_ (putStrLn) $ snd w

但我一直得到上​​述类型错误......

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

只需使用bind而不是runVmEval m = do (a,w) <- evalRWST run () () putStrLn "End" mapM_ putStrLn w

{{1}}