2012-02-29 31 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)