TrueLogic 仕事日記 このページをアンテナに追加 RSSフィード

2013-02-03Stateモナドで信号器

Stateモナドを使って信号器を書いて見た.ログの内容を伝搬(追記)させるには,bindに手を入れるしかないのかな?

import Control.Monad.State

data Signal = Green | Yellow | Red deriving Show

move :: State Signal String
move = state $ \s ->
  let f = show s ++ "==>" in
  case s of Green -> (f ++ "Yellow", Yellow)
            Yellow -> (f ++ "Red", Red)
            Red -> (f ++ "Green",Green)

moveMainp :: State Signal String
moveMainp = do
  move
  move
  
main :: IO()
main = do
  putStrLn $ show $ runState move Red
  putStrLn $ show $ runState move Green
  putStrLn $ show $ runState move Yellow
  putStrLn $ show $ runState moveMainp Red
  putStrLn "Done."

実行結果


$ ghc traffic-signal
$ ./traffic-signal 
("Red==>Green",Green)
("Green==>Yellow",Yellow)
("Yellow==>Red",Red)
("Green==>Yellow",Yellow)
Done.

トラックバック - http://specverification.g.hatena.ne.jp/n757uf/20130203