经过了几次Haskell的作业后,发现concatMap对于list的作用极其强大,下面就具体讲解一下concatMap的作用:
1.concatMap定义及类型:
- Map a function over a list and concatenate the results.
- 将函数映射到列表并连接结果
- concatMap :: (a -> [b]) -> [a] -> [b]
2.Map定义及类型:
- returns a list constructed by appling a function (the first argument) to all items in a list passed as the second argument
- 返回一个通过将函数(a->b)应用于作为第二个参数([a])传递的列表中的所有项而构造的列表
- (a -> b) -> [a] -> [b]
3.举例说明
Prelude> map (enumFromTo 1) [1,3,5]
[[1],[1,2,3],[1,2,3,4,5]]
Prelude> concatMap (enumFromTo 1) [1,3,5]
[1,1,2,3,1,2,3,4,5]
Prelude> map (\x -> [(x,x+2,x/2)]) [1,3,5]
[[(1.0,3.0,0.5)],[(3.0,5.0,1.5)],[(5.0,7.0,2.5)]]
Prelude> concatMap (\x -> [(x,x+2,x/2)]) [1,3,5]
[(1.0,3.0,0.5),(3.0,5.0,1.5),(5.0,7.0,2.5)]
从上述例子中,可以看出concatMap就是将map的结果连接成为一个list。
其实,concatMap就是利用foldr函数,将(++)函数与f复合为foldr函数的第一个参数:
concatMap :: (a -> [b]) -> [a] -> [b]
concatMap f = foldr ((++) . f) []
想一下,给你一个list如何给每一个元素末尾加上“!”??
利用concatMap可以巧妙解决这一问题:
Prelude> concatMap (++"! ") ["one", "two", "three"]
"one! two! three! "
Prelude> concatMap (++"!") ["one", "two", "three"]
"one!two!three!"