Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
285 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...