列表操作
函数 | 类型签名 | 说明 | 例子 |
---|---|---|---|
head |
[a] -> a |
取列表第一个元素 | head [1,2,3] = 1 |
tail |
[a] -> [a] |
去掉列表第一个元素 | tail [1,2,3] = [2,3] |
init |
[a] -> [a] |
去掉列表最后一个元素 | init [1,2,3] = [1,2] |
last |
[a] -> a |
取列表最后一个元素 | last [1,2,3] = 3 |
length |
[a] -> Int |
计算列表长度 | length [1,2,3] = 3 |
null |
[a] -> Bool |
判断列表是否为空 | null [] = True |
reverse |
[a] -> [a] |
翻转列表 | reverse [1,2,3] = [3,2,1] |
take |
Int -> [a] -> [a] |
取前 n 个元素 | take 2 [1,2,3] = [1,2] |
drop |
Int -> [a] -> [a] |
丢弃前 n 个元素 | drop 2 [1,2,3] = [3] |
splitAt |
Int -> [a] -> ([a],[a]) |
分割列表为两部分 | splitAt 2 [1,2,3] = ([1,2],[3]) |
filter |
(a -> Bool) -> [a] -> [a] |
过滤满足条件的元素 | filter even [1..5] = [2,4] |
map |
(a -> b) -> [a] -> [b] |
对列表每个元素应用函数 | map (+1) [1,2,3] = [2,3,4] |
foldl |
(b -> a -> b) -> b -> [a] -> b |
从左到右折叠 | foldl (+) 0 [1,2,3] = 6 |
foldr |
(a -> b -> b) -> b -> [a] -> b |
从右到左折叠 | foldr (:) [] [1,2,3] = [1,2,3] |
zip |
[a] -> [b] -> [(a,b)] |
两个列表配对成元组列表 | zip [1,2] ['a','b'] = [(1,'a'),(2,'b')] |
zipWith |
(a -> b -> c) -> [a] -> [b] -> [c] |
两个列表的对应元素分别应用一个函数,返回一个新列表 | zipWith (+) [1,2] [3,4] = [4,6] |
concat |
[[a]] -> [a] |
合并列表的列表 | concat [[1,2],[3]] = [1,2,3] |
concatMap |
(a -> [b]) -> [a] -> [b] |
对列表每个元素应用函数,返回一个新列表 | concatMap (\x -> [x,x]) [1,2,3] = [1,1,2,2,3,3] |
elem |
Eq a => a -> [a] -> Bool |
判断元素是否在列表中 | elem 3 [1,2,3] = True |
notElem |
Eq a => a -> [a] -> Bool |
判断元素不在列表中 | notElem 4 [1,2,3] = True |
takeWhile |
(a -> Bool) -> [a] -> [a] |
从头取满足条件的元素 | takeWhile (<3) [1,2,3] = [1,2] |
dropWhile |
(a -> Bool) -> [a] -> [a] |
从头丢弃满足条件的元素 | dropWhile (<3) [1,2,3] = [3] |
span |
(a -> Bool) -> [a] -> ([a], [a]) |
从头分割列表,前部分满足条件,后部分不满足,在第一次不满足条件时停止 | span (<3) [1,2,3] = ([1,2],[3]) |
all |
(a -> Bool) -> [a] -> Bool |
判断列表所有元素是否满足条件 | all (<3) [1,2,3] = True |
\\ |
(a -> Bool) -> [a] -> [a] |
列表差集操作符 | [1,2,3] \\ [1,2] = [3] |
flip |
(a -> b -> c) -> b -> a -> c |
翻转函数参数顺序 | flip (++) "word" " hello" = "hello word" |
2025年6月14日大约 14 分钟