问题描述
特别是我在这里查看问题 1
Specifically I'm looking at Problem 1 here
http://pavelfatin.com/scala-for-project-euler/
代码如下
val r = (1 until 1000).view.filter(n => n % 3 == 0 || n % 5 == 0).sum
我可以关注除了查看"之外的所有内容.事实上,如果我取出视图,代码仍然可以编译并产生完全相同的答案.
I can follow everything except for "view". In fact if I take out view the code still compiles and produces exactly the same answer.
推荐答案
View 产生一个惰性集合,因此调用例如filter
不会评估集合的每个元素.元素仅在显式访问后才进行评估.现在 sum
确实访问了所有元素,但是使用 view
调用 filter
不会创建完整的 Vector.(见史蒂夫的评论)
View produces a lazy collection, so that calls to e.g. filter
do not evaluate every element of the collection. Elements are only evaluated once they are explicitly accessed. Now sum
does access all elements, but with view
the call to filter
doesn't create a full Vector. (See comment by Steve)
使用视图的一个很好的例子是:
A good example of the use of view would be:
scala> (1 to 1000000000).filter(_ % 2 == 0).take(10).toList
java.lang.OutOfMemoryError: GC overhead limit exceeded
这里 Scala 尝试创建一个包含 1000000000
元素的集合,然后访问前 10 个元素.但是使用视图:
Here Scala tries to create a collection with 1000000000
elements to then access the first 10. But with view:
scala> (1 to 1000000000).view.filter(_ % 2 == 0).take(10).toList
res2: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
这篇关于在 Scala 中,什么是“视图"?做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!