Chris Stewart Chris Stewart - 1 year ago 48
Scala Question

How can I generate a subset of the elements of a sequence?

How can I pick a subset of the elements of a sequence?

For instance, if I had the sequence

, I'd like each call to my generator to produce something like






How can I define such a generator?

Answer Source

org.scalacheck.Gen.someOf is a generator that picks a random number of elements from an iterable:

scala> import org.scalacheck.Gen
import org.scalacheck.Gen

scala> val baseSeq = Seq(1, 2, 3, 4, 5)
baseSeq: Seq[Int] = List(1, 2, 3, 4, 5)

scala> val myGen = Gen.someOf(baseSeq).map(_.toSeq)
myGen: org.scalacheck.Gen[Seq[Int]] = org.scalacheck.Gen$$anon$6@ff6a218

scala> myGen.sample.head
res0: Seq[Int] = List(3, 4, 5)

scala> myGen.sample.head
res1: Seq[Int] = List(1, 2, 3, 4)

scala> myGen.sample.head
res2: Seq[Int] = List()