我是haskell的新手,我有以下代码
module StateTest where
import Control.Monad.State.Lazy
tick :: State Int Int
tick = do n <- get
put (n+1)
return n
plusOne :: Int -> Int
plusOne = execState tick
main = print $ plusOne 1
Run Code Online (Sandbox Code Playgroud)
我想在之后打印状态值put (n+1)并继续这样的计算
tick = do n <- get
put (n+1)
print
return n
Run Code Online (Sandbox Code Playgroud)
整个代码如何看待这个?
如果要在状态计算中运行IO操作,可以更改tick返回a StateT Int IO Int和use 的类型liftIO.然后你可以运行它execStateT:
import Control.Monad.State.Lazy
import Control.Monad.IO.Class (liftIO)
tick :: StateT Int IO Int
tick = do n <- get
put (n+1)
liftIO $ print (n+1)
return n
plusOne :: Int -> IO Int
plusOne = execStateT tick
main = plusOne 1 >> pure ()
Run Code Online (Sandbox Code Playgroud)