Skip to content

Instantly share code, notes, and snippets.

@guojh
Last active December 16, 2015 01:19
Show Gist options
  • Save guojh/5354766 to your computer and use it in GitHub Desktop.
Save guojh/5354766 to your computer and use it in GitHub Desktop.
Homework of Foundations for Programming Languages http://staff.ustc.edu.cn/~yuzhang/fpl/
module Main where
import Random
import System.IO
-- To make an executable called "Guesser"
-- >ghc --make Guesser.hs
-- Note that the function
-- getRandom :: (Int, Int) -> IO Int
-- is defined in the module Random
-- Other useful functions:
-- putStrLn :: String -> IO () -- Print string to output
-- getLine :: IO String -- Reads a line of input
-- read :: Read t => String -> t -- Parse any type t belonging to Read class to a value of type t
logFileName = "guess.log"
untilIO :: IO Bool -> IO ()
untilIO action = action >>= \x -> if x then return () else untilIO action
readInt :: String -> IO Int
readInt str = return (read str)
doGuess :: Int -> IO Bool
doGuess secret =
getLine >>= readInt >>= \x ->
let result = x == secret
msg = if x == secret
then "Congratulations!"
else if x < secret
then "Too low!"
else "Too high!"
in do
putStrLn msg
appendFile logFileName (show x ++ "\n")
return result
main :: IO ()
main = do
secret <- getRandom(1,10)
putStrLn "I'm thinking of a number between 1 and 10. Can you guess it?"
h <- openFile logFileName WriteMode
hClose h
untilIO (doGuess secret)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment