Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScalaCheck - Ordered array generator

I am trying out ScalaCheck for the first time and I want to generate an ordered array of Ints.

I read the documentation and did some search but I didn't find a way to do it.

Can someone shed some light on this?

Thanks

like image 616
rmorais Avatar asked Mar 15 '15 08:03

rmorais


1 Answers

I assume you want an arbitrary array of integers that's been sorted, right? If that's the case, you can use either of the following approaches to get a Gen[Array[Int]]:

val genIntArray = Gen.containerOf[Array, Int](
  Gen.chooseNum(Int.MinValue, Int.MaxValue)
)

Or:

val genIntArray = implicitly[Arbitrary[Array[Int]]].arbitrary

You can then use map to modify the generator to sort its results:

 val genSortedIntArray = genIntArray.map(_.sorted)

Now you can run genSortedIntArray.sample.get a few times to convince yourself that the result is a sorted array of random integers.

If you want an Arbitrary for sorted arrays of integers, it's best to define a wrapper instead of hiding the default Arbitrary[Array[Int]]. For example, you could write the following:

case class SortedIntArray(value: Array[Int]) extends AnyVal

object SortedIntArray {
  implicit val arb: Arbitrary[SortedIntArray] = Arbitrary(
    genSortedIntArray.map(SortedIntArray(_))
  )
}

And then:

forAll { (a: SortedIntArray) =>
  confirmThatMyFunctionOnSortedIntArraysWorks(a.value)
}
like image 170
Travis Brown Avatar answered Nov 06 '22 08:11

Travis Brown