Task

Write a game (computer program) that follows the following rules:

 The computer chooses a number between given set limits.
 The player is asked for repeated guesses until the the target number is guessed correctly
 At each guess, the computer responds with whether the guess is:
 higher than the target,
 equal to the target, 
 less than the target,   or
 the input was inappropriate. 


Related task

   Guess the number/With Feedback (Player)


 
import Control.Monad
import System.Random
 
-- Repeat the action until the predicate is true.
until_ act pred = act >>= pred >>= flip unless (until_ act pred)
 
answerIs ans guess =
  case compare ans guess of
    LT -> putStrLn "Too high. Guess again." >> return False
    EQ -> putStrLn "You got it!" >> return True
    GT -> putStrLn "Too low. Guess again." >> return False
 
-- Repeatedly read until the input *starts* with a number.  (Since
-- we use "reads" we allow garbage to follow it, though.)
ask = do line <- getLine
         case reads line of
           ((num,_):_) -> return num
           otherwise -> putStrLn "Please enter a number." >> ask
 
main = do
  ans <- randomRIO (1,100) :: IO Int
  putStrLn "Try to guess my secret number between 1 and 100."
  ask `until_` answerIs ans
 