map
和的flatMap
功能有什么区别Iterable
?
5 回答
以上都是正确的,但还有一件事很方便: flatMap
将 aList[Option[A]]
变成List[A]
,将任何Option
向下钻取到None
,删除。这是超越使用null
.
这是一个很好的解释:
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)
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.
看这里: http: //www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-2
“搜索 flatMap” - 那里有一个很好的解释。(基本上它是“扁平化”和“地图”的组合——来自其他语言的特征)。