import System.IO
-- 有副作用的函數類型 IO a, 其元素是完成一些動作,然後返回一個類型a的值的程序
-- putStr :: String -> IO ()
-- () :: ()
-- ↑值 ↑類型
{-
:t getLine
:t getChar
:t putChar
-}
-- p >> q 表示先做p,再做q
p1 :: IO () -- 顯示一個串"hello ",再顯示一個串"there!\n"
p1 = putStr "hello " >> putStrLn "there!\n" -- putStr "there!\n"
-- putStrLn :: String -> IO()
-- putStrLn str = putStr (str ++ "\n")
-- getLine :: IO String
p2 :: IO ()
p2 = do putStr "Input some words:"
s <- getLine
putStrLn $ "you typed " ++ s
-- 對齊
-- 膜dalao
my_p2 :: IO ()
my_p2 = do putStr "Input your name: "
s <- getLine
putStrLn $ s ++ " is just " ++ "dalao."
-- The End
p3 :: IO ()
p3 = do putStr "Input some int: "
s <- getLine
putStr "Input another int: "
t <- getLine
let k = (read s :: Int) + (read t :: Int)
putStrLn ("The sum is " ++ show k)
-- putStrLn ("The sum is " ++ show ((read s :: Int) + (read t :: Int)) ++ ".")
-- return :: a -> IO a
-- return x = IO a
p4 :: IO Int
p4 = do putStr "Input some int: "
s <- getLine
return (read s :: Int)
p5 :: IO() -- A clearer p3
p5 = do x <- p4
y <- p4
putStrLn ("The sum is: " ++ show (x + y))
-- Call sb SB
my_SB :: IO ()
my_SB = do putStr "Input your name: "
s <- getLine
putStrLn $ s ++ " SB."
-- The End
-- readFile :: FilePath -> IO String
-- writeFile :: FilePath -> String -> IO ()
-- appendFile :: FilePath -> String -> IO ()
p6 :: IO ()
p6 = do
s <- readFile "atext.txt"
putStrLn s
p7 :: IO ()
p7 = do
appendFile "atext.txt" "Hello there\n"
-- append something in txt
my_p7 :: IO ()
my_p7 = do
putStr "Input what you want to append: "
s <- getLine
appendFile "atext.txt" $ s ++ "\n"
-- The End
{-
putStr :: String -> IO ()
putStr [] = return ()
putStr (x:xs) = do putChar x
putStr xs
-}
{-
getLine :: IO String
getLine = do x <- getChar
if x == '\n'
then return []
else do xs <- getLine
getLine -- ...
-}
{-
sumInt :: IO Int
sumInt = do putStrLn "Input a int(if you input 0, sum ends): "
n <- p4 -- getInt
if n == 0 return n
else
-}
-- Guess the word
getCh :: IO Char
getCh = do hSetEcho stdin False
c <- getChar
hSetEcho stdin True
putChar '*'
return c
sgetLine :: IO String
sgetLine =
do
x <- getCh
if (x == '\n') then
do return []
else do
xs <- sgetLine
return (x:xs)
hangman :: IO ()
hangman = do
putStrLn "Input a word"
word <- sgetLine
guess word
guess :: String -> IO ()
guess word =
do putStr "Guess the word: "
xs <- getLine
if xs == word then putStrLn "You got it!"
else do putStrLn (diff word xs)
guess word
diff :: String -> String -> String
diff xs ys = [if elem x ys then x else '-' | x <- xs]
{-
guess :: IO String
guess = do s <- getLine
putStrLn "Try to guess the word: "
t <- getLine
let x = length [y | n <- [1..] , take n s == take n t]
-}
Haskell筆記(11.16)|IO program
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.