内置变量
模块
:m Data.Char Data.Map
加载模块
chr
ord
toUpper
toLower
import Data.Char
导入到全局命名空间
import Data.List (nub, sort)
import Data.List hiding (nub)
import qualified Data.Map as M
这样其中命名冲突的filter, null函数,只能用Data.Map.filter或M.filter方式调用
可用模块
自定义模块
module Geometry.Sphere
( sphereVolume
, sphereArea
, Shape (..)
# 导出类型和其所有构造子
) where
sphereVolum :: Float -> Float
sphereVolum radius = ( 4.0 / 3.0 ) * pi * (radius ^ 3 )
内置函数
prelude
$
函数调用符,优先级最低。而空格是最高优先级
$右结合。而空格左结合
等价于在右而写一对括号
.
f . g = \x → f (g x)
函数组合
main
signum
not
id
unlines
unwords
show
read
read "5" :: Int
read “5” - 2
read “[1,2,3]” ++ [4]
reads
negate
abs
length
列表的长度, [a] → Int , a在这里是一个type variable, 以小写字母开头(具体类型都大写开头)
map
compare
min
max
compare
返回LT, GT, EQ
"Abc" `compare` "Zyx"
mod
odd
even
succ
pred
minBound
maxBound
substract
head
tail
last
init
null
reverse
take
takeWhile
drop
maximum
minimun
sum
product
elem
判断元素是否在list中
4 `elem` [ 3 , 4 , 5 ]
cycle
repeat
replicate
fst (1, 2)
snd (1, 2)
zip
zip3, zip4 … zip7
zip [1,2,3] [4,5,6]
zipWith
zipWith1 … zipWith7
zipWith (\x y → x + y) [1,2] [3,4]
fromIntegral
error ""
flip
map
filter
foldl
foldl (\acc x → acc + x) 0 xs
foldr
foldr (\x acc → f x : acc) [] xs
foldl1
foldr1
foldl’
foldr’
scanl
scanr
scanl1
scanr1
o→ I/O action
只有在main中执行
类型为 IO a
putStrLn
只接受String,不转义打印,加换行符
putStrLn :: String -> IO () , 表示接收String, 是IO动作, 结果类型是()。表示是一个”IO monad”动作
putStr
putChar
print
getLine
控制台读一行
getLine :: IO String
name ← getLine
getChar
sequence
mapM
mapM_
getContents
interact
Data.List
每个元素存在thunk中
\
差集
[1..3] \ [2]
“Im a big baby” \ “big”
union
intersection
insert
nub
map
filter
intersperse
intercalate
transpose
foldl’
fold的严格版,直接计算出中间值,而非用惰性”承诺”塞满堆栈
foldl1’
concat
concatMap
先map再concat
concatMap (replicate 2) [1..3]
and
list中全true返回true
and $ map (>4) [5,6,7,8]
or
any
iterate
无限迭代值到函数,结果形成list
take 10 $ iterate (*2) 1
splitAt
断开list, 返回二元组
splitAt 3 “abcdef”
takeWhile
dropWhile
span
同takeWhile, 不过返回分割list的二元组
break
sort
group
inits
tails
isInfixOf
list中搜索子list, 有则返回true
"cat" `isInfixOf` "im a cat"
isPrefixOf
isSuffixOf
elem
notElem
partition
条件划分list为二元组
partition ( `elem` [ 'A' .. 'Z' ]) "AbCD"
find
条件查找list, 返回第一个符合元素的Maybe值
elemIndex
elemIndices
findIndex
findIndices
lines
unlines
words
unwords
delete
删除list中第一个匹配元素
delete ‘h’ “hha”
replace
lookup
genericLength
genericTake
genericDrop
genericSplitAt
genericIndex
genericReplicate
nubBy
deleteBy
unionBy
intersectBy
groupBy
sortBy
insertBy
maximumBy
minimumBy
Data.Monoid
Monoid
Product
Sum
Any
All
Data.Foldable
foldr
foldl
foldr1
foldl1
Data.Function
on
(( == ) `on` ( > 0 ))
判断相等性,等价于 (\x y → (x > 0) == (y > 0))
(compare `on` length)
Data.Char
isControl
isSpace
isLower
isUpper
isAlpha
isAlphaNum
isPrint
isDgit
isOctDigit
isHexDigit
isLetter
isMark
isNumber
isPunctuation
isSymbol
isSeperater
isAscii
isLatin1
isAsciiUpper
isAsciiLower
GeneralCategory
得到字符的分类,一共31类, 属于Eq类型
generalCategory ’ ’
toUpper
toLower
toTitle
digitToInt
intToDigit
ord
char
Data.Map
用avl树实现
fromList
fromListWith
toList
empty
insert
insertWith
null
size
singleton
lookup
member
map
filter
keys
elems
Data.Set
要求元素可排序,自动排序、唯一
用avl树实现
fromList
intersection
difference
union
null
size
member
empty
singleton
insert
delete
isSubsetOf
子集
fromList [1,2] isSubsetOf fromList [1,2]
isProperSubsetOf
filter
map
Data.ByteString
strict bytestring
Empty相当于[], cons相当于:
Data.ByteString.Lazy
每个元素存在chunk中,每个chunk 64k,每个chunk相当于一个strict bytestring
cons在chunk不满的时候会新建chunk, cons’是strick版的cons, 会填充chunk
pack
pack :: [Word8] -> ByteString
pack [80,81]
unpack
fromChunks
转换strick bytestring 到lazy
toChunks
Data.Ratio
Control.Applicative
Applicative
class ( Functor f) => Applicative f where
pure :: a -> fa
(<*>) :: f (a -> b) -> f a -> f b
f <$> x = fmap f x
ZipList
getZipList
liftA2
liftA2 f x y = f <$> x <*> y
sequenceA
Control.Monad
when
Bool true时,返回后面的I/O action, 否则return ()
forever
不断执行后面的I/O action
forever $ do
forM
liftM
liftM2 liftM3 liftM4 liftM5
`ap`
join
join :: ( Monad m) => m (m a) -> m a
join mm = do
m <- mm
m
filterM
foldM
Control.Monad.State
State
newtype State s a = State {runState :: s -> (a, s)}
get
put
Control.Monad.Error
System.IO
openFile
openFile :: FilePath -> IOMode -> IO Handle
data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode
do
handle = openFile "a.txt" ReadMode
contents <- hGetContents handle
putStr contents
hClose handle
withFile
withFile :: FilePath -> IOMode -> (Handle -> IO a) -> IO a
处理完关掉
withFile "a.txt" ReadMode ( \ handle -> do
contents <- hGetContents handle
putStr contents)
readFile
readFile :: FilePath -> IO String
do
contents <- readFile "a.txt"
putStr contents
wirteFile
writeFile :: FilePath -> String -> IO ()
do
writeFile "a.txt" contents
appendFile
hSetBuffering
读binary file时的buffer,默认是系统值
data BufferMode = NoBuffering | LineBuffering | BlockBuffering (Maybe Int)
hSetBuffering handle $ BlockBuffering (Just 2048)
hFlush
openTempFile
(tempName, tempHandle) ← openTempFile ”.” “temp”
hGetContents
hClose
hGetLine
hPusStr
hPutStrLn
hGetChar
System.IO.Error
catch
catch :: IO a -> (IOError -> IO a) -> IO a
toTry `catch` handler
handler e
| isDoesNotExistError e =
case ioeGetFileName e of Just path -> putStrLn $ "a" ++ path
Nothing -> putStrLn "b"
| otherwise = ioError e
isDoesNotExistError
isAlreadyExistsError
isFullError
isEOFError
isIllegalOperation
isPermissionError
isUserError
ioeGetFileName
ioeGetFileName :: IOError -> Maybe FilePath
ioError
System.Directory
removeFile
renameFile
renameFile tempName “a.txt”
copyFile
doesFileExist
System.Environment
System.Random
mkStdGen
mkStdGen :: Int -> StdGen
getStdGen
IO类型, 得到系统启动时的global generator
newStdGen
把现有的random generator分成两个新的generators, 其中一个指定成新的,返回另一个
random
random :: (RandomGen g, Random a) = g -> (a, g)
random (mkStdGen 100) :: (Int, StdGen)
randoms
take 5 $ randoms (mkStdGen 11) :: [Int]
randomR
区间random
randomR (1,6) (mkStdGen 2)
randomRs
take 10 $ randomRs ('a', 'z') (mkStdGen 3) :: [Char]