do block 的返回值必须是 IO <something>

return :: a -> IO a 是一个函数

value <- something 表明 something :: IO Xvalue :: 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 opb 为真时,执行 op
  • unless :: Bool -> IO () -> IO ()
    • unless b opb 为假时,执行 op
  • replicateM :: Int -> IO a -> IO [a]
    • replicateM num opop 执行 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
-- split string into lines
lines :: String -> [String]

-- `isSuffixOf suf list` is true if list ends in suf
Data.List.isSuffixOf :: Eq a => [a] -> [a] -> Bool

-- `isInfixOf inf list` is true if inf occurs inside list
Data.List.isInfixOf :: Eq a => [a] -> [a] -> Bool

-- FilePath is just an alias for String
type FilePath = String

-- get entire contents of file
readFile :: FilePath -> IO String

-- list files in directory
System.Directory.listDirectory :: FilePath -> IO [FilePath]

-- is the given file a directory?
System.Directory.doesDirectoryExist :: FilePath -> IO Bool

IORef

The Haskell type IORef a from the module Data.IORef is a mutable reference to a value of type a

1
2
3
4
5
6
7
8
9
10
11
-- create a new IORef containing a value
newIORef :: a -> IO (IORef a)

-- produce value contained in IORef
readIORef :: IORef a -> IO a

-- set value in IORef
writeIORef :: IORef a -> a -> IO ()

-- modify value contained in IORef with a pure function
modifyIORef :: IORef a -> (a -> a) -> IO ()