ScalaCheck - ordered array generator

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

I read the documentation and did a search, but did not find a way to do this.

Can someone shed some light on this?

thanks

+6
source share
1 answer

I assume that you need an arbitrary array of integers that has been sorted, right? In this case, you can use any of the following approaches to get Gen[Array[Int]] :

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

Or:

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

Then you can use map to change the generator to sort its results:

  val genSortedIntArray = genIntArray.map(_.sorted) 

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

If you want Arbitrary for sorted arrays of integers, it's best to define a wrapper instead of hiding the default Arbitrary[Array[Int]] . For example, you can 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) } 
+7
source

Source: https://habr.com/ru/post/983813/


All Articles