Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a scala BitSet from a range

Tags:

scala

I'd like to initialize a scala BitSet to contain the integers from 1 to N. The following will work, but I'm looking for a better solution:

var s = BitSet.empty ++ (1 to n)

I was hoping that I could do something like this:

var s:BitSet = (1 to n).toSet

...but that results in an error:

error: polymorphic expression cannot be instantiated to expected type;
  found   : [B >: Int]scala.collection.immutable.Set[B]
  required: scala.collection.immutable.BitSet

Am I missing something obvious?

like image 933
Mike Avatar asked Jun 16 '11 04:06

Mike


1 Answers

Thats what breakOut is for:

val s: BitSet = (1 to n).map(identity)(breakOut)

See this question to understand the inner working of breakOut.

Another solution is to use the constructor of BitSet:

val s = BitSet((1 to n): _*)

the : _* tells the compiler that you want to use the Range as repeated parameters.

Because breakOut looks ugly you can use the pimp-my-library pattern to produce nicer looking code (as described here):

val s = (1 to n).to[BitSet]
like image 96
kiritsuku Avatar answered Oct 16 '22 19:10

kiritsuku