Haskell笔记(6)
2016-11-16 20:29
106 查看
有副作用的函数类型 IO a,其元素是完成一些动作,然后返回一个类型a的值的程序.
–putStr :: String -> IO()–() :: ()
–putChar :: Char -> IO()
–getLine :: IO String
–getChar :: IO Char
–p >> q,表示先做p,再做q
–显示“hello”再显示“there!”
p1 :: IO()
p1 = putStr “hello” >> putStr “there!\n”
–putStrLn :: String -> IO()
–读一个字符串,显示一个字符串
p2 :: IO()
p2 = do putStr “input some words: ”
s <- getLine 一行表示一个动作,每一行要对齐
putStrLn (“your type” ++ s) 或 putStrLn $ “your type” ++ s
p3 :: IO()
p3 = do putStr “input some int: ”
s <- getLine
putStr “input some int: ”
t <- getLine
let k = (read s :: Int) + (read t :: Int)
putStrLn (“the sum is ” ++ show k)
–return :: a -> IO a
–return x :: IO a
–读一个字符串,返回一个整数
p4 :: IO Int
p4 = do putStr “input some int: ”
s <- getLine
return (read s :: Int)
FilePath : 文件名或带路径的文件名
打开文件并读出文件的内容,返回文件内容
readFile :: FilePath -> IO String
p6 :: IO()
p6 = do s <- readFile “input1.txt”
putStrLn s (显示出input1.txt里面的内容)
向文件里添加内容(会覆盖掉原文件的内容)
writeFile :: FilePath -> String -> IO()
向文件里添加内容(不会覆盖掉原文件的内容)
appendFile :: FilePath -> String -> IO()
p7 :: IO()
p7 = do appendFile “input1.txt” “hello there\n”
统一动作的循环
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
return (x: xs)
循环的实现:输入一个整数,直至遇到0,然后统计总和。
不断读入整数,直至遇到0,然后统计总和。
sumInts :: IO Int
sumInts
=do n <- getInt
if n == 0
then return 0
else (do m <- sumInts
return (n + m))
sumInteract :: IO()
sumInteract
= do putStrLn “Enter intergers one per line”
putStrLn “These will be summed until zero is entered”
sum <- sumInts
putStr “The sum was ”
print sum
读入一个整数:
getInt :: IO Int
getInt = do line <- getLine
return (read line :: Int)
相关文章推荐
- Haskell语言学习笔记(39)Category
- Haskell语言学习笔记(46)Parsec(3)
- Haskell语言学习笔记(3)map, filter, fold
- Haskell语言学习笔记(25)MonadState, State, StateT
- haskell学习笔记_函数
- Haskell学习笔记1
- Haskell语言学习笔记(34)System.Environment
- Haskell 笔记(四)函数系统
- haskell笔记
- Haskell语言学习笔记(40)Arrow(1)
- Haskell语言学习笔记(47)Arrow(2)
- Haskell学习笔记 --- 理解 max :: (Ord a) => a -> (a -> a)
- Haskell : Functionally Solving Problems 部分学习笔记
- haskell笔记1
- Haskell语言学习笔记(26)Identity, IdentityT
- Haskell 笔记 ③
- haskell笔记(1)
- Haskell 笔记(三)类型系统
- Monad State in Haskell 笔记
- haskell学习笔记(8)-haskell的类型系统