Haskell常用模组

2016-09-20
1分钟阅读时长

Haskell标准库查询 Hoogle Hooyoo

Data.List

Data.List所有函数

intersperse '.' "MONKEY"
-- 数组每个元素中间插入一个元素
transpose [[1,2,3][4,5,6]]
-- 转置矩阵
foldl'
foldl1'
-- 惰性实现的严格版本, 具体见 Haskell指南
concatMap (replicate 4) [1..3]
-- concat $ map
and [True, True]
or [False, True]
any (>4) [1,2,3,4]
all (>4) [5,6,7,8]

take 10 $ iterate (*2) 1
-- iterate 会产生无限序列
splitAt 3 "heyman"

takeWhile (>3) ([6,5..1])
dropWhile (>3) ([6,5..1])
span (>3) ([6,5..1] ++ [1..6])
break (<3) ([6,5..1] ++ [1..6])
-- span 会在 False 后直接断开, 若要遍历整个 List 用 partition
Data.List.partition (`elem` ['A'..'Z']) "Hello, World!"

Data.List.sort [9,8..0]
Data.List.group ([9,8..0] ++ [0..5])
Data.List.group $ Data.List.sort ([9,8..0] ++ [0,1..5])
-- 注意以上两句的区别

Data.List.inits "wo00t"
Data.List.tails "wo00t"
let w = "w00t" in zip (Data.List.inits w) (Data.List.tails w)

"cat" `Data.List.isInfixOf` "im a cat burglar"
"im " `Data.List.isPrefixOf` "im a cat burglar"
"lar" `Data.List.isSuffixOf` "im a cat burglar"
'c' `elem` "cat"
'r' `notElem` "cat"

-- 以下 Maybe/List 类型相关
Data.List.find (>4) [1..6]
Data.List.findIndex (==4) [5,3,4,1,6,4]
Data.List.findIndices (==4) [5,3,4,1,6,4]
4 `Data.List.elemIndex` [5,4..1]
4 `Data.List.elemIndices` ([5,4..1] ++ [1..5])

Data.List.lines "first line\nsecond line"
Data.List.unlines ["first line", "second line"]
Data.List.words "first-word second-word"
Data.List.unwords ["first-word", "second-word"]

Data.List.nub "Lots of words and stuff"
Data.List.delete 'e' "hey there"

[1..10] Data.List.\\ [2,5,9]
([1..10]++[10,9..1]) Data.List.\\ [2,5,9]
"hey man" `Data.List.union` "hey what's up"
[1..7] `Data.List.intersect` [5..10]

insert 4 [1,2,3,5,6,7,8] -- 排序

Data.List.genericLength       -- length(Int)的通用版本(Num)
-- 类似还有 take, drop, splitAt, index

Data.List.nubBy -- Data.List.nubBy (==) 等价于 Data.List.nub
-- 类似还有 delete, union, intersect, group
let values = [-4.3, -2.4, -1.2, 0.4, 2.3, 5.9, 10.5, 29.1, -2.4, -14.5, 2.2]
Data.List.groupBy (\x y -> (x > 0) == (y > 0)) values
Data.List.groupBy ((==) `Data.Function.on` (> 0)) values

let xs = [[5,4,5,4,4], [1,2,3], [3,5,4,3], [], [2], [2,2]]
Data.List.sortBy (compare `Data.Function.on` length) xs

Data.Char

Data.Char.isControl     -- 控制字符
Data.Char.isSpace
Data.Char.isUper
Data.Char.isLower
Data.Char,isAlpha
Data.Char.isAlphaNum
Data.Char.isPrint
Data.Char.isDigit
Data.Char.isOctDigit
Data.Char.isHexDigit
Data.Char.isLetter
Data.Char.isMark        -- unicode注音字符(法语)
Data.Char.isNumber
Data.Char.isPunctuation -- 标点
Data.Char.isSymbol      -- 货币符号
Data.Char.Seperater
Data.Char.isAscii
Data.Char.isLatin1
Data.Char.isAsciiUpper
Data.Char.isAsciiLower
-- 类型均为 Char -> Bool

-- 判断字符串使用
all Data.Char.isAlphaNum "bobby123"

Data.Char.generalCategory -- 输出字符类型
Data.Char.generalCategory ' '
-- Char -> GeneralCategory (为 Eq 类型的一部分)
下一页 Haskell指南

相关