用一些数据来做我State'
的程序状态。
type State' m a = StateT Int m a
我会在一些计算中使用它。
例子:
-- genData, return some string (using Int value and State')
genData :: Int -> State' String
genData n = ...
-- genDatas, return multiple strings
genDatas :: Int -> State' [String]
genDatas n = mapM genData [1..n]
-- printLog, write log message (enumerating lines)
printLog :: String -> State' IO ()
printLog msg = do
n <- get
let n' = n + 1
put n'
liftIO $ putStrLn $ "Message #" ++ (show n') ++ ": " ++ msg
我认为这不是正确的方法:
-- If I need a "in context function" returning a Int value...
--
-- addExtra, return current Int in state plus x
addExtra :: Int -> State' Identity Int
addExtra x = get >>= return.(+x)
要addExtra
在某些 monad 上下文中使用我的函数,我会这样做:
doComplex :: State' IO ()
doComplex = do
printLog "Starting process..."
-- It's ugly!
s <- get
Identity (w, s') <- return $ runStateT (addExtra 5) s
put s' -- save state
printLog $ "computed value: " ++ (show w)
沿着不同功能共享我的State'
monad 的正确方法是什么?(就像IO a
做的那样)
谢谢!
(我已经阅读了一些教程和一些源代码,但我无法理解)