Taking Notes from http://learnyouahaskell.com
IO
- 你能把 I/O action 想成是一个长了脚的盒子,它会跑到真实世界中替你做某些事
- 打开盒子的唯一办法就是用 <-
- 一个 I/O action 会在我们把它绑定到 main 这个名字并且运行程序的时候触发
- do 表示法将所有 I/O action 绑成一个
Hello World
hello world 来的晚了点 :)
|
|
|
|
- return an I/O action
- it container () () means return nothing
|
|
Let Binding
|
|
- let bindings in expression (in expression is not required)
Example
|
|
- return () means it return an IO ()
- return will not stop program
|
|
Some IO methods
- putStr :: String -> IO ()
- putChar
- putStrLn
- print
- 接受任何是 Show typeclass 的 instance 的型态的值
- putStrLn 会打印出”, print不会
- getChar :: IO Char
When
- import Control.Monad will import when
|
|
sequence
sequence :: [IO a] -> IO [a]
|
|
mapM mapM_ forM
由于对一个串列 map 一个回传 I/O action 的函数,然后再 sequence 他这个动作太常用了
- mapM 接受一个函数跟一个串列,将对串列用函数 map 然后 sequence 结果
- mapM_ 也作同样的事,只是他把运算的结果丢掉而已
|
|
forever
- forever 接受一个 I/O action 并回传一个永远作同一件事的 I/O action
- import Control.Monad
|
|
Stream
- getChar
- getLine
- getContents :: IO String
|
|
File
|
|
- openFile :: FilePath -> IOMode -> IO Handle
- type FilePath = String
- data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode
|
|
- withFile :: FilePath -> IOMode -> (Handle -> IO a) -> IO a
|
|
|
|
- writefile :: FilePath -> String -> IO ()
|
|
Other functions:
- hGetLine
- hPutStr
- hPutStrLn
- hGetChar
Random
|
|
System IO action1234567import System.Randommain = do gen <- getStdGen putStr $ take 20 (randomRs ('a','z') gen) gen' <- newStdGen putStr $ take 20 (randomRs ('a','z') gen')