-- based on http://scsibug.com/2006/11/28/a-simple-game-with-statet/ -- by tphyahoo@gmail.com module Main where import System.Random import Control.Monad.State import Control.Exception main = do answer <- getStdRandom (randomR (1,100)) -- think of a number putStrLn "I'm thinking of a number between 1 and 100, can you guess it?" guesses StateT Int IO () guessSession answer = do g do lift $ putStrLn "Too low" guessSession answer GT -> do lift $ putStrLn "Too high" guessSession answer EQ -> lift $ putStrLn "Got it!" where getInt = getLine >>= readM "getInt, bad input" safeGetInt = handle ( \e -> do putStrLn "bad input, try again" safeGetInt ) getInt -- inspired (but not quite the same) as stuff in Neil Mitchell's "safe haskell" lib -- http://hackage.haskell.org/cgi-bin/hackage-scripts/package/Safe-0.1 readM msg s = case [x | (x,t) <- reads s, ("","") return x [] -> fail $ "Prelude.read: no parse, " ++ msg ++ ", on " ++ prefix _ -> fail $ "Prelude.read: ambiguous parse, " ++ msg ++ ", on " ++ prefix where prefix = '\"' : a ++ if null b then "\"" else "..." where (a,b) = splitAt 10 s