Vikas Singh
Vikas Singh

Reputation: 3028

Use of View in Scala

I was solving the problem Filter Positions in a List:(For a given list with integers, return a new list removing the elements at odd positions)

I came up with

arr.zipWithIndex.filter(_._2 %2 == 1).map(_._1)

But someone has suggested that below code would be faster

arr.view.zipWithIndex.filter{ _._2 % 2 != 0 }.map { _._1}.force.toList

I know, View creates unconditional collection(Lazies evaluation), But at which step (Method call) it will help us. Meaning:

arr.view, creates view on which zipWithIndex will work, and zipWithIndex will process each element to create Map of value and Index. I guess till now, no optimization.

filter method has to work on every element then it only it can skip or select it. I am not sure, how adding view in this case would help.

Upvotes: 0

Views: 170

Answers (1)

puhlen
puhlen

Reputation: 8529

Using view means that all the operations can happen at once, instead of one at a time.

arr.zipWithIndex.filter(_._2 %2 == 1).map(_._1)

This works, but it creates 3 new lists in the process, first it runs the zipWithIndex producing a new list with the result. Then passes than new list to the filter, creating another list, and finally calls map on that list producing the final list.

So in that we creates two intermediate lists that we don't really need.

arr.view.zipWithIndex.filter{ _._2 % 2 != 0 }.map { _._1}.force.toList

This version uses view so if can perform all those operations in one shot, without needing to create those intermediate collections at each step.

Upvotes: 3

Related Questions