2012-02-29 49 views
0

我发现这部分在http://www.haskell.org/haskellwiki/State_Monad 但我不清楚我将如何定义c和f的初始状态。如何定义State Monad中的初始状态?

虽然它与IORefs一起工作,但我不需要全局可变数据。

increment :: StateT Integer IO Integer 
increment = do 
     n <- get 
     put (n+1) 
     return n 

plusOne :: Integer -> IO Integer 
plusOne n = execStateT increment n 

printTChan mtch = do 
     forever $ do 
     m <- atomically $ readTChan mtch 
     case m of 
      "ping" -> plusOne c 
      _ -> plusOne f 
     print (c) 
+2

你看过'runState'吗? – Ingo 2012-02-29 22:47:51

回答

7

StateT工作,你能想到的run/eval/execStateT为庆祝国家的范围,所以你有什么有写这只是一种奇特的方式:因为你是

plusOne n = return (n+1) 

忽略这些行为的结果,这没有任何影响。

如果你想在您的整个计算携带状态,你需要组织你的代码,以便在整个事件中StateT运行:

printTChan mtch = flip evalStateT (c0, f0) $ do 
    forever $ do 
     m <- liftIO . atomically $ readTChan mtch 
     case m of 
      "ping" -> modify incrementC 
      _  -> modify incrementF 
     (c, f) <- get 
     liftIO $ print c 

incrementC (c, f) = (c+1, f) 
incrementF (c, f) = (f, c+1) 

现在,你可以在初始状态值填写的地方的(c0, f0)