{- October 4, 2006 Preparatory Course for the Software Technology Master Bastiaan Heeren (bastiaan@cs.uu.nl), Universiteit Utrecht, The Netherlands -} module Guess where import Data.Char (isDigit) import System.Random (newStdGen, randomRs) -- First, we create a random number generator. This generator is used -- to generate a list of random numbers between 0 and 100. We are only -- interested in the head of this list. main :: IO () main = do rng <- newStdGen let nr:_ = randomRs (0,100) rng putStrLn "Which number between 0 and 100 do I have in mind?" guess nr 1 -- The input from the user is validated first: the string should not be -- empty, nor should it contain characters that are not digits. guess :: Int -> Int -> IO () guess nr turn = do putStr "? " input <- getLine if null input || any (not . isDigit) input then guess nr turn else eval (read input) where eval :: Int -> IO () eval i | i < nr = do putStrLn ("The number is larger than " ++ show i) guess nr (turn+1) | i > nr = do putStrLn ("The number is smaller than " ++ show i) guess nr (turn+1) | otherwise = do putStrLn ("Congratulations: you got the number in " ++ show turn ++ " turns!")