State Monad:如何在Haskell中“打印"中间值 [英] State monad: How to `print` intermediate value in Haskell
本文介绍了State Monad:如何在Haskell中“打印"中间值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Haskell的新手,我有以下代码
I'm new in haskell and I have following code
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
我想在put (n+1)
之后打印状态值并继续这样计算
And I want to print state value after put (n+1)
and continue computation like this
tick = do n <- get
put (n+1)
print
return n
遵循此规则的整个代码看起来如何?
How whole code will look following to this?
推荐答案
如果要在状态计算中运行IO操作,则可以更改tick
的类型以返回StateT Int IO Int
并使用liftIO
.然后,您可以使用execStateT
:
If you want to run IO actions within a state computation you can change the type of tick
to return a StateT Int IO Int
and use liftIO
. Then you can run it using 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 ()
这篇关于State Monad:如何在Haskell中“打印"中间值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文