Chris Stewart Chris Stewart - 3 months ago 24
Scala Question

How can I define a ScalaCheck generator that produces a subset of a sequence's elements?

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

For instance, if I had the sequence

Seq(1,2,3,4,5)
, I'd like each call to my generator to produce something like

Seq(1,4)


or

Seq(1,2,3,5)


or

Seq()


How can I define such a generator?

Answer

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()
Comments