Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

haskell - Number guessing game error and keeping count of guesses

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...