Just a quick program since it’s been some time since I updated my blog!
module Main where import System.Random main :: IO () main = do putStrLn "Try to guess the secret word ([1-100])..." secret <- randomRIO (1, 100) play secret play :: Int -> IO () play secret = do guesses <- playGame secret 0 putStrLn $ "You win! You took " ++ show guesses ++ " guesses!" playGame :: Int -> Int -> IO Int playGame secret guesses = do putStr "? " input <- getLine let guess = read input :: Int if guess == secret then do return (guesses + 1) else if guess < secret then do putStrLn "Too small!" playGame secret (guesses + 1) else do putStrLn "Too big!" playGame secret (guesses + 1)
The code is pretty straightforward – the only tricky part I faced was implementing the random number generation (quite a complicated topic in Haskell).
$ ghc guessingGame.hs [1 of 1] Compiling Main ( guessingGame.hs, guessingGame.o ) Linking guessingGame ... $ ./guessingGame Try to guess the secret word ([1-100])... 50 ? Too small! 75 ? Too big! 63 ? Too big! 56 ? Too small! 59 ? Too small! 61 ? You win! You took 6 guesses!
Exciting, eh? 🙂