让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)
要在某些monad上下文中使用我的addExtra
函数,我会这样做:
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
所做的那样)
谢谢!
(我已经阅读了一些教程和一些源代码,但我无法理解)
答案 0 :(得分:5)
由于你的addExtra
函数实际上并没有对底层monad做任何事情,你可以只改变类型签名以使其与monad-annostic无关:
addExtra :: Monad m => Int -> State' m Int
addExtra x = get >>= return . (+x)
现在你可以写这个
doComplex :: State' IO ()
doComplex = do
printLog "Starting process..."
w <- addExtra 5
printLog $ "Computed value: " ++ show w
哪个更漂亮,就像你的旧代码一样:
*Main> runStateT doComplex 0
Message #1: Starting process...
Message #2: Computed value: 6
((),2)
我可能想要将addExtra
重写为以下之一。首先,使用do notation
addExtra x = do s <- get
return (s + x)
或使用liftM
,因为我们并没有真正使用我们拥有monad的事实
addExtra x = liftM (+x) get
甚至使用gets
(感谢Daniel Wagner在评论中)
addExtra x = gets (+x)
当然,到目前为止,您可能不需要额外的功能。你也可以写一下
doComplex = do printLog "Starting process..."
w <- gets (+5)
printLog $ "Computed value: " ++ show w
同样,我可能会重写printLog
。如果你发现自己get
处于状态,对它做了些什么,并put
回来,你可能只想使用modify
。
printLog msg = do modify (+1)
n <- get
liftIO . putStrLn $ "Message #" ++ show n ++ ": " ++ msg