In Scala, what does “browse” do?

In particular, I address problem 1 here

http://pavelfatin.com/scala-for-project-euler/

The code below is as follows

val r = (1 until 1000).view.filter(n => n % 3 == 0 || n % 5 == 0).sum 

I can keep track of everything except the "submission." In fact, if I choose a view, the code is still compiling and giving exactly the same answer.

+48
scala
Jul 23 2018-11-11T00:
source share
2 answers

View creates a lazy collection, so calls like filter do not evaluate each element of the collection. Elements are evaluated only after their direct access. sum now accesses all elements, but with view calling filter does not create a full vector. (See Comment from Steve)

A good example of using a view would be:

 scala> (1 to 1000000000).filter(_ % 2 == 0).take(10).toList java.lang.OutOfMemoryError: GC overhead limit exceeded 

Here Scala is trying to create a collection with 1000000000 items to access the first 10. But with a 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) 
+76
Jul 23 '11 at 10:19
source share

I don't know much about Scala, but maybe this page can help ...

There are two main ways to implement transformers. One of them is strict, that is, a new collection with all its elements was built as a result of a transformer. The other is non-strict or lazy, that is, one creates only a proxy server to collect results, and its elements are created only on demand.

A view is a special kind of collection, which is a basic collection, but lazily implements all transformers.

It sounds as if the code will work without a view , but theoretically you can do some extra work by building all the elements of your collection in a rigorous rather than lazy way.

+19
Jul 23 '11 at 10:20
source share



All Articles