do block 的返回值必须是 IO <something>.
return :: a -> IO a 是一个函数
value <- something 表明 something :: IO X 且 value :: X,并且只能在 do block 内使用
putStr/putStrLn打印字符串getLine :: IO String获取输入print :: Show a => a -> IO ()利用show :: a -> String进行打印readLn :: Read a => IO a利用read从终端输入读取数据
Control.Monad 还有很多实用的流程控制:
when :: Bool -> IO () -> IO ()when b op当b为真时,执行op
unless :: Bool -> IO () -> IO ()unless b op当b为假时,执行op
replicateM :: Int -> IO a -> IO [a]replicateM num op将op执行num次,并收集结果
replicateM_ :: Int -> IO a -> IO ()- 类似,但是丢弃结果
mapM, mapM_ :: (a -> IO b) -> [a] -> IO [b] / IO ()- 对列表的每一个元素都执行操作
forM, forM_ :: [a] -> (a -> IO b) -> IO [b] / IO ()- 一样,只是参数顺序不一样
文件 IO:
1 | -- split string into lines |
IORef
The Haskell type IORef a from the module Data.IORef is a mutable reference to a value of type a
1 | -- create a new IORef containing a value |