2012-02-29 4 views
0

これは部分的にhttp://www.haskell.org/haskellwiki/State_Monad にありますが、どのようにしてcとfの初期状態を定義するのかはわかりません。State Monadでの初期状態の定義方法を教えてください。

これはIORefsで動作しますが、グローバルな変更可能なデータは必要ありません。

StateTで作業する場合、あなたはあなたがこれを書いているだけの空想の方法がある持っているので、どのような、状態の範囲をマーキングとして run/eval/execStateTと考えることができ
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

答えて

7

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)です。

関連する問題