第六章:常用的列表操作

夢飛發表於2017-02-26

列表的定義限定了列表中的型別一定都是相同的。

1.對映

把從a到b的函式對映成了從[a]到[b]的函式,這個函式保留了元素的一一對應關係。

map :: (a -> b) ->[a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs

enter image description here

2.過濾

filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter p xs = [ x | x <- xs, p x]

3.摺疊

fold——map-reduce,把一個列表聚合成一個的操作,幾乎所有遞迴處理列表的函式都可以通過摺疊來實現。摺疊式順序遞迴操作的物件。

foldr :: (a -> b -> b) -> b -> t a -> b
foldr  _ aac [] = aac
foldr f aac (x:xs) = foldr f x (f aac  xs)

foldl :: (a -> b -> b) -> b -> t a -> b
foldl  _ aac [] = aac
foldl f aac (x:xs) = foldl f (f aac x) xs

4.掃描

把摺疊時每一步的累計值都記錄下來,生成一個新的列表

scanl :: (b -> a -> b) -> b -> [a] -> [b]
scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]

last (scanl f z xs) == foldl f z xs
head (scanr f z xs) == foldr f z xs

enter image description here

5.方向是相對的

如何使用foldr實現foldl?

相關文章