RSS

StateTを使う(応用編)

こんな感じでユーザーの入力で足し算をするプログラムを書いてみた。StateTを使ってIOを処理している。

import Control.Monad.State
import Control.Exception
import Prelude hiding (catch)
import System.IO

count :: StateT Int IO ()
count = do 
  n <- get
  l <- liftIO $ do
    putStrLn $ "Total =  " ++ (show n)
    putStr $ "Input integer or 'q' >> "
    hFlush stdout
    getLine
  if l == "q" then
    return ()
    else do
    num <- liftIO $ (readIO l) `catch` 
                     (\e -> return (e::SomeException) >> 
                            putStrLn "parse error" >> return 0)
                            
    modify (+num)
    count

main = do
  s <- execStateT count 0
  putStrLn $ "Final total = " ++ (show s)