Last active
December 16, 2015 01:19
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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