Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't scala's parallel sequences have a contains method?

Why does

 List.range(0,100).contains(2)

Work, while

 List.range(0,100).par.contains(2)

Does not?

This is planned for the future?

like image 517
placeybordeaux Avatar asked Jun 01 '12 00:06

placeybordeaux


1 Answers

The non-teleological answer is that it's because contains is defined in SeqLike but not in ParSeqLike.

If that doesn't satisfy your curiosity, you can find that SeqLike's contains is defined thus:

def contains(elem: Any): Boolean = exists (_ == elem)

So for your example you can write

List.range(0,100).par.exists(_ == 2)

ParSeqLike is missing a few other methods as well, some of which would be hard to implement efficiently (e.g. indexOfSlice) and some for less obvious reasons (e.g. combinations - maybe because that's only useful on small datasets). But if you have a parallel collection you can also use .seq to get back to the linear version and get your methods back:

List.range(0,100).par.seq.contains(2)

As for why the library designers left it out... I'm totally guessing, but maybe they wanted to reduce the number of methods for simplicity's sake, and it's nearly as easy to use exists.

This also raises the question, why is contains defined on SeqLike rather than on the granddaddy of all collections, GenTraversableOnce, where you find exists? A possible reason is that contains for Map is semantically a different method to that on Set and Seq. A Map[A,B] is a Traversable[(A,B)], so if contains were defined for Traversable, contains would need to take a tuple (A,B) argument; however Map's contains takes just an A argument. Given this, I think contains should be defined in GenSeqLike - maybe this is an oversight that will be corrected.

(I thought at first maybe parallel sequences don't have contains because searching where you intend to stop after finding your target on parallel collections is a lot less efficient than the linear version (the various threads do a lot of unnecessary work after the value is found: see this question), but that can't be right because exists is there.)

like image 133
Luigi Plinge Avatar answered Sep 19 '22 14:09

Luigi Plinge