Skip to content

Instantly share code, notes, and snippets.

@pete-murphy
Created May 25, 2019 02:53
Show Gist options
  • Save pete-murphy/7558c13165b2fd3ee9d8f81d40444470 to your computer and use it in GitHub Desktop.
Save pete-murphy/7558c13165b2fd3ee9d8f81d40444470 to your computer and use it in GitHub Desktop.
module FPtoMax where
import Data.Char
import System.Random
import Text.Read
main :: IO ()
main = do
putStrLn "What is your name?"
name <- getLine
putStrLn $ "Hello, " ++ name ++ ", welcome to the game!"
guessLoop name
guessLoop :: String -> IO ()
guessLoop name = do
num <- getStdRandom (randomR (1, 5)) :: IO Int
putStrLn $ "Dear " ++ name ++ ", please guess a number from 1 to 5:"
handleGuess name num
handleGuess :: String -> Int -> IO ()
handleGuess name num = do
guess <- readMaybe <$> getLine :: IO (Maybe Int)
case guess of
Just x
| x == num -> putStrLn $ "You guessed right, " ++ name ++ "!"
| otherwise ->
putStrLn $
"You guessed wrong, " ++ name ++ "! The number was: " ++ show num
Nothing -> putStrLn "That's not a number!" >> handleGuess name num
putStrLn $ "Do you want to continue, " ++ name ++ "?"
handleContinue name
handleContinue :: String -> IO ()
handleContinue name = do
continue <- getLine
case toLower <$> continue of
"y" -> guessLoop name
"n" -> pure ()
_ -> putStrLn "Please answer 'y' or 'n':" >> handleContinue name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment