I have been trying to learn Haskell myself over the past few weeks. I am currently trying to implement a dumb game in which the computer selects a random number and the user tries to guess it. If the user is mistaken, the program informs the user that the answer is higher or lower and allows the user to guess until they guess correctly. It works for me, but I would like to add the ability to track the number of guesses that the user makes each game, and report this number to them as soon as they guess correctly.
Based on an imperative background, it would be natural to have a counter that increments every time the user makes an assumption, but you cannot do it in Haskell (at least it looks like statelessness and the immutability of all this will prevent).
I played with the idea of โโmaking the getGuess and giveHints functions take an additional parameter that will show the number of guesses (let's call it numGuesses), and pass (numGuesses + 1) with each call to these methods. But I could not get this to work (not to mention the fact that I did not even know if it would work).
My code is below. Any suggestions would be really appreciated. I'm mostly looking for ideas, but feel free to post the actual code too. Also feel free to let me know if my code sucks and how I could improve it if you notice anything disgusting (I only programmed for a couple of weeks!)
import System.Random import System.IO import Control.Monad main = do gen <- getStdGen let (ans,_) = randomR (1,100) gen :: (Int,StdGen) putStrLn $ "I'm thinking of a number between 1 and 100..." getGuess ans putStrLn "You guessed it in __ guesses!" putStr "Play again? " hFlush stdout desire <- getLine when ((desire !! 0) `elem` ['y','Y']) $ do putStrLn "" newStdGen main getGuess ans = do putStr "Your guess? " hFlush stdout guessStr <- getLine giveHints ans (read guessStr) giveHints ans guess = do when (ans /= guess) $ do if ans > guess then putStrLn "It higher." else putStrLn "It lower." getGuess ans
Note. I use hflush stdout because I use line buffering, and without it, the order of some interactions is not what you would expect.
mkfarrow
source share