“Monads 允许程序员使用顺序构建 block 来构建计算”,因此它允许我们组合一些计算。如果是这样,那为什么下面的代码不能运行呢?
import Control.Monad.Trans.State
gt :: State String String
gt = do
name <- get
putStrLn "HI" -- Here is the source of problem!
put "T"
return ("hh..." ++ name ++ "...!")
main= do
print $ execState gt "W.."
print $ evalState gt "W.."
最佳答案
Monad 转换器是将不同功能放入 monad 的机制。
monad 只知道如何组合该 monad 能力范围内的计算。您不能在 State
中执行 I/O monad,但你可以在 StateT s IO a
单子(monad)。但是,您需要使用 liftIO
关于进行 I/O 的计算。
import Control.Monad.Trans.State
import Control.Monad.IO.Class (liftIO)
gt :: StateT String IO String
gt = do
name <- get
liftIO $ putStrLn "HI"
put "T"
return ("hh..." ++ name ++ "...!")
main = do
print =<< execStateT gt "W.."
print =<< evalStateT gt "W.."
关于haskell - Monad 与 Monad 变压器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45082178/