Learn You a Haskell for Great Good 读书笔记 8

8. Input & Output

1
2
3
4
5
6
7
8
9
import Data.Char
main = do
putStrLn "What's your first name?"
firstName <- getLine
putStrLn "What's your last name?"
lastName <- getLine
let bigFirstName = map toUpper firstName
bigLastName = map toUpper lastName
putStrLn $ "hey " ++ bigFirstName ++ " " ++ bigLastName ++ ", how are you?"

do 意味着后面进行IO操作

<- 是IO操作,左边取IO行为的结果。

let 与之前的一样,绑定数值。

return 将右边的值作为IO结果返回,如 wahaha <- return “wahaha”

when
1
2
3
4
import Control.Monad
main = do
input <- getLine
when (input == "SWORDFISH") $ do putStrLn input

参数为一个布尔和一个IO行为,布尔为True的时候才进行IO行为,否则返回IO()

sequence
1
sequence $ map print [1, 2, 3, 4, 5]

将一组IO行为按顺序进行,并输出结果

mapM & mapM_

相当于sequence $ map,右边不会输出结果

forever

while(true) $ do any IO action…

forM
1
forM :: (Monad m, Traversable t) => t a -> (a -> m b) -> m (t b)