Specifically I'm looking at Problem 1 here
http://pavelfatin.com/scala-for-project-euler/
The code as listed is as follows
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.
Unlike operations directly on a concrete collection like List , operations on Iterator are lazy. A lazy operation does not immediately compute all of its results.
The Stream is a lazy lists where elements are evaluated only when they are needed. This is a scala feature. Scala supports lazy computation. It increases performance of our program. Streams have the same performance characteristics as lists.
To convert a list into a map in Scala, we use the toMap method. We must remember that a map contains a pair of values, i.e., key-value pair, whereas a list contains only single values. So we have two ways to do so: Using the zipWithIndex method to add indices as the keys to the list.
In Scala flatmap method is used on the collection and data structures of scale, as the name suggests it is the combination of two things methods i.e. map and Flatten method. If we use a flat map on any collection then it will apply both this method map and flatten method on the given collection.
I don't know much about Scala, but perhaps this page might help...
There are two principal ways to implement transformers. One is strict, that is a new collection with all its elements is constructed as a result of the transformer. The other is non-strict or lazy, that is one constructs only a proxy for the result collection, and its elements get constructed only as one demands them.
A view is a special kind of collection that represents some base collection, but implements all transformers lazily.
So it sounds as if the code will still work without view
, but might in theory be doing some extra work constructing all the elements of your collection in strict rather than lazy fashion.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With