Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Scala have SeqView but not SetView?

Given that Seq.view returns a SeqView, I would have expected Set.view to return a SetView, but no such view exists; Set.view instead returns an IterableView.

Unfortunately, IterableView is missing some methods, such as contains. Compare these, for example:

Seq(1, 2, 3).view.map(_ * 2).contains(4) // returns true
Set(1, 2, 3).view.map(_ * 2).contains(4) // error

Is there any particular reason why no SetView class exists?

Also, is there any reason why Iterable doesn't have a contains method (given this is basically a special case of find)?

Given the situation above, is there a better alternative to this when working with sets (in other words, what is the best practice in Scala):

Set(1, 2, 3).view.map(_ * 2).find(_ == 4).isDefined
like image 911
dsiegmann Avatar asked Nov 01 '22 15:11

dsiegmann


1 Answers

There is no SetView because views are a pain in the neck to implement and test, and that effort is less worth it since the nice properties of sets generally require you to have already eagerly created the entire set (e.g. O(1) or O(log n) lookup).

contains isn't in Iterable precisely because Set extends Iterable and a Set contains should not type check unless you ask for something that could be in the set. Since Iterable is covariant, its contains would have to admit you asking for anything (as the contains for Seq does).

As a workaround, you can note that contains(x) does the same thing as exists(_ == x), and exists is on Iterable.

like image 102
Rex Kerr Avatar answered Nov 08 '22 09:11

Rex Kerr