Number guessing game error and keeping count of gu

2019-09-21 10:00发布

问题:

I am doing a number guessing game in Haskell and I have 3 difficulties.
I made a menu where the user selects what difficulty but once I implemented it, it started giving me an error and I can't figure out what it is.
The error:

finalename.hs:5:10:
Parse error in pattern: putStrLn
Possibly caused by a missing 'do'?

Also how would I go about implementing a count where it counts how many times it takes for the user to guess?

import System.Random (randomRIO)     
main :: IO ()
main = do
     putStrLn "Do you want to play 1) Easy, 2) Medium or 3) Hard"
     putStrLn "Select your difficulty by entering a number 1, 2 or 3"
     choice <- readLn
       | choice == 1 = "You selected easy" >> easy
       | choice == 2 = "You selected medium" >> medium
       | choice == 3 = "You selected hard" >> hard
       | otherwiose = "You did not selected a valid choice" >> main

easy :: IO ()
easy = do
     putStrLn "Guess a number between 1 and 13: "
     rNumber <- randomRIO (1, 10) :: IO Int
     loop rNumber

medium :: IO ()
medium = do
     putStrLn "Guess a number between 1 and 25: "
     rNumber <- randomRIO (1, 25) :: IO Int
     loop rNumber

hard :: IO ()
hard = do
     putStrLn "Guess a number between 1 and 50: "
     rNumber <- randomRIO (1, 50) :: IO Int
     loop rNumber

loop :: Int -> IO ()
loop rNumber = do
       userInput <- readLn 
       case compare rNumber userInput of
         EQ -> putStrLn "Correct!" >> main
         LT -> putStrLn "Guess is too low, try again please" >> loop rNumber
         GT -> putStrLn "Guess is too high, try again please" >> loop rNumber

回答1:

You need to change your loop function to keep track of both the number to guess and the number of guesses:

loop :: Int -> Int -> IO ()
loop rNumber guesses = do
  putStrLn $ "You have made " ++ show guesses ++ " guesses so far."
  ...
  putStrLn "Too low, guess again"
  loop rNumber (guesses+1)
  ...
  putStrLn "To high, guess again"
  loop rNumber (guesses+1)

Note how when you call loop recursively you change the guess count by passing in the old guess count + 1.