2

假设我们有一些 int 值(正值和负值)的列表,并且我们的任务是仅将正值加倍。这是产生所需结果的片段:

val list: List[Int] = ....

    list.filter(_ > 0).map(_ * 2)

到目前为止一切都很好,但是如果列表非常大,大小为 N 怎么办?程序是否在 filter 函数上迭代 N 次,然后在 map 函数上迭代 N 次?

scala 如何知道何时需要循环遍历列表并应用所有过滤和映射内容?如果我们通过标识函数(例如去除重复项)和应用映射函数对原始列表进行分组,将会产生什么结果(就列表遍历而言)?

4

3 回答 3

3

程序是否在 filter 函数上迭代 N 次,然后在 map 函数上迭代 N 次?

是的。使用视图使对集合的操作变得惰性。例如:

val list: List[Int] = ...
list.view.filter(_ > 0).map(_ * 2)

scala 如何知道何时需要循环遍历列表并应用所有过滤和映射内容?

使用视图时,它会在您实际使用物化值时计算值:

val x = list.view.filter(_ > 0).map(_ * 2)
println(x.head * 2)

这仅在调用 head 时应用过滤器和映射。

于 2013-10-26T00:26:03.067 回答
2

程序是否在 filter 函数上迭代 N 次,然后在 map 函数上迭代 N 次?

是的,List你应该使用withFilter。来自withFilter文档:

Note: the difference between `c filter p` and `c withFilter p` is that
      the former creates a new collection, whereas the latter only
      restricts the domain of subsequent `map`, `flatMap`, `foreach`,
      and `withFilter` operations.
于 2013-10-26T00:02:51.803 回答
2

如果有mapafter filter,您可以随时使用collect

list.filter(0<).map(2*)

list.collect{ case x if x > 0 => 2*x }
于 2013-10-26T09:54:57.433 回答