您的位置:首页 > 其它

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)  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: