Skip to content

Instantly share code, notes, and snippets.

@etorreborre
Last active October 7, 2019 10:59
Show Gist options
  • Save etorreborre/d0616e704ed85d7276eb12b025df8ab0 to your computer and use it in GitHub Desktop.
Save etorreborre/d0616e704ed85d7276eb12b025df8ab0 to your computer and use it in GitHub Desktop.
Generate a list of distinct elements from a Scalacheck generator
import scala.collection.mutable.ListBuffer
import org.scalacheck._, Arbitrary._, Prop._
// a specs2 example showing that it works
def e1 =
forAll(distinctListOf[Int]) { ls =>
ls.distinct === ls
}.set(minTestsOk = 10000, maxSize = 1000)
// distinct list of elements from a given arbitrary
def distinctListOf[T : Arbitrary] =
distinctListOfGen(arbitrary[T])
// distinct list of elements from a given generator
// with a maximum number of elements to discard
def distinctListOfGen[T](gen: Gen[T], maxDiscarded: Int = 1000): Gen[List[T]] = {
val seen: ListBuffer[T] = new ListBuffer[T]
var discarded = 0
Gen.sized { size =>
if (size == seen.size) seen.toList
else {
while (seen.size <= size && discarded < maxDiscarded)
gen.sample match {
case Some(t) if !seen.contains(t) =>
seen.+=:(t)
case _ => discarded += 1
}
seen.toList
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment