Advertisement
Guest User

game

a guest
Dec 8th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import System.Random
  2. import Control.Monad
  3.  
  4. -- A type for the possible results (C programmers would call this an enum)
  5. data Result = Lower | Match | Higher
  6.  
  7. -- The simple game logic
  8. game :: Integer -> Integer -> Result
  9. game guess secret
  10.  | guess == secret = Match
  11.  | guess < secret = Lower
  12.  | guess > secret = Higher
  13.  
  14. -- Map the result to a message for the user
  15. mapResult :: Result -> String
  16. mapResult Lower  = "Number too low"
  17. mapResult Higher = "Number too high"
  18. mapResult Match  = "You've got it!"
  19.  
  20. -- trying to read a Int from stdin
  21. readAInt :: IO Integer
  22. readAInt = readLn
  23.  
  24. computeSecret :: IO Int
  25. computeSecret = getStdRandom (randomR (1,100))
  26.  
  27. mainloop = do
  28.     secret <- computeSecret
  29.     guess <- readAInt
  30.     putStrLn ("input: " ++ (show guess))
  31.     putStrLn ("secret: " ++ (show secret))
  32.     --readAInt $ computeSecret $ game
  33.     --unless (guess == 0) $ do
  34.     result <- game guess secret
  35.     output <- mapResult result
  36.     putStrLn output
  37.     mainloop
  38.  
  39. main = do
  40.     putStrLn "Guess a number between 1 and 100"
  41.     mainloop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement