RSS

Stateモナドを使う

こんな感じで。

import Control.Monad.State

--count :: State Int String
count :: State Int ()
count = do 
  n <- get
  put (n+1)
  return ()

countP :: StateT Int IO ()
countP = do 
  n <- get
  liftIO $ putStrLn $ "0: " ++ (show n)
  put (n+1)
  n <- get 
  liftIO $ putStrLn $ "1: " ++ (show n)
  return ()

main = do
  print $ runState count 1
  putStrLn "---"
  print $ evalState count 1
  putStrLn "---"
  print $ execState count 1
  putStrLn "---"
  print $ runState count (execState count 2)
  putStrLn "---"
  print $ runState (sequence [count,count]) 1
  putStrLn "---"
  runStateT countP 1
  putStrLn "---"
  runStateT (sequence [countP, countP]) 10
  return ()

出力結果。

((),2)
---
()
---
2
---
((),4)
---
([(),()],3)
---
0: 1
1: 2
---
0: 10
1: 11
0: 11
1: 12