–有副作用的函数类型 IO a , 表示执行一次I/O(input/output)后返回一个类型为a的值
–IO () 指返回()类型的值,或认为它不返回值
基本IO操作
–putStr :: String -> IO ()
–putChar :: Char -> IO ()
–getLine :: IO String –返回值是输入的String
–getChar :: IO Char
–print <==> putStrLn.show
—p>>q , 先完成p , 再完成q
–显示两个字符串
p1 :: IO ()
p1 = putStr “HELLO ” >> putStr “WORLD!\n” —输入p1执行这个
–putStrLn :: String -> IO ()
相当于 putStr 加上\n , 上句也可写成putStrLn “WORLD!”
– a<-b将b的返回值赋给a
–读一个字符串,显示一个字符串
—想要多个操作,用do,do后的语句要对齐
p2 :: IO ()
p2 = do putStrLn “input some words:”
s <- getLine
putStrLn (“your typed is ” ++ s)
或 putStrLn
"yourtypedis"++s−−−
能降低优先级
p3 = do putStrLn “input some int”
s <- getLine
putStrLn “input another int”
t <- getLine
let k = (read s :: Int) + (read t :: Int)
putStrLn (“the sum is ” ++ show k)
–return :: a -> IO a
–输出一个值a
p4 :: IO Int
p4 = do putStrLn “input some int”
s <- getLine
return (read s :: Int) —Int 用 return
–p3改成
p3 :: IO ()
p3 = do x <- p4
y <- p4
putStrLn (“the sum: ” ++ show (x+y))
–readFile :: FilePath -> IO String
FilePath 指文件名或带路径的文件名,type FilePath = String
readFile 读取文件,并将文件内容以字符串形式
p6 :: IO ()
p6 = do s <- readFile “input 1.txt”
putStrln s
–writeFile :: FilePath -> String -> IO () 覆盖式写入 String指要写入的内容
–appendFile 追加式写入
p7 :: IO ()
p7 = do write “input 1.txt” “hello world\n”
–不断地输入整数,直到遇到0,然后统计其和
sumInts :: IO Int
sumInts = do n <- getInt
if n == 0
then return 0
else (do m <- sumInts
return (n+m))
—then和else后的动作类型必须一致,且以do开始,除非只有一个动作
getInt :: IO Int
getInt = do line <-getLine
return (read line :: Int)
sumInteract :: IO ()
sumInteract = do putStrLn “input one integer per line”
sum <- sumInts
putStrLn $ “the sum is ” ++ sum