58

map和的flatMap功能有什么区别Iterable

4

5 回答 5

57

以上都是正确的,但还有一件事很方便: flatMap将 aList[Option[A]]变成List[A],将任何Option向下钻取到None,删除。这是超越使用null.

于 2009-06-29T20:37:49.747 回答
44

这是一个很好的解释:

http://www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-2

以列表为例:

地图的签名是:

map [B](f : (A) => B) : List[B]

而flatMap是

flatMap [B](f : (A) => Iterable[B]) : List[B]

所以 flatMap 接受一个类型 [A] 并返回一个可迭代类型 [B],而 map 接受一个类型 [A] 并返回一个类型 [B]

这也将使您了解 flatmap 将“展平”列表。

val l  = List(List(1,2,3), List(2,3,4))

println(l.map(_.toString)) // changes type from list to string
// prints List(List(1, 2, 3), List(2, 3, 4))

println(l.flatMap(x => x)) // "changes" type list to iterable
// prints List(1, 2, 3, 2, 3, 4)
于 2009-06-29T20:33:13.140 回答
8

scaladoc

  • 地图

返回将给定函数 f 应用于此可迭代对象的每个元素所产生的可迭代对象。

  • 平面图

将给定的函数 f 应用于此迭代的每个元素,然后连接结果。

于 2009-06-29T18:39:59.683 回答
8
lines.map(line => line split "\\W+") // will return a list of arrays of words
lines.flatMap(line => line split "\\W+") // will return a list of words

你可以在理解中更好地看到这一点:

for {line <- lines
     word <- line split "\\W+"}
yield word.length

这转化为:

lines.flatMap(line => line.split("\\W+").map(word => word.length))

Each iterator inside for will be translated into a "flatMap", except the last one, which gets translated into a "map". This way, instead of returning nested collections (a list of an array of a buffer of blah, blah, blah), you return a flat collection. A collection formed by the elements being yield'ed -- a list of Integers, in this case.

于 2009-06-29T20:38:38.247 回答
3

看这里: http: //www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-2

“搜索 flatMap” - 那里有一个很好的解释。(基本上它是“扁平化”和“地图”的组合——来自其他语言的特征)。

于 2009-06-29T19:21:36.250 回答