Chapter 5

  1. Define an invariant property for sorting a list.
def invariant[T: Ordering: Arbitrary]: Prop =
forAll((l: List[T]) => l.sorted.length == l.length)

scala> invariant[Long].check
+ OK, passed 100 tests.

scala> invariant[String].check
+ OK, passed 100 tests.
  1. Define an idempotent property for sorting a list.
def idempotent[T: Ordering: Arbitrary]: Prop =
forAll((l: List[T]) => l.sorted.sorted == l.sorted)

scala> idempotent[Long].check
+ OK, passed 100 tests.

scala> idempotent[String].check
+ OK, passed 100 tests.
  1. Define an inductive property for sorting a list.
def inductive[T: Ordering: Arbitrary]: Prop = {
def ordered(l: List[T]): Boolean =
(l.length < 2) ||
(ordered(l.tail) && implicitly[Ordering[T]].lteq(l.head, l.tail.head))
forAll((l: List[T]) => ordered(l.sorted))
}

scala> inductive[Int].check
+ OK, passed 100 tests.

scala> inductive[String].check
+ OK, passed 100 tests.
  1. Define a generator for List[Lists[Int]] so that elements of the nested list are positive.
val genListListInt = Gen.listOf(Gen.listOf(Gen.posNum[Int]))

scala> genListListInt.sample
res35: Option[List[List[Int]]] = Some(List(List(60, 99, 5, 68, 52, 98, 31, 29, 30, 3, 91, 54, 88, 49, 97, 2, 92, 28, 75, 100, 100, 38, 16, 2, 86, 41, 4, 7, 43, 70, 21, 72, 90, 59, 69, 43, 88, 35, 57, 67, 88, 37, 4, 97, 51, 76, 69, 79, 33, 53, 18), List(85, 23, 4, 97, 7, 50, 36, 24, 94), List(97, 9, 25, 34, 29, 82, 59, 24, 94, 42, 34, 80, 7, 79, 44, 54, 61, 84, 32, 14, 9, 17, 95, 98), List(4, 70, 13, 18, 42, 74, 63, 21, 58, 4, 32, 61, 52, 77, 57, 40, 37, 54, 11), List(9, 22, 33, 19, 56, 29, 45, 34, 61, 48, 42, 56, 64, 96, 56, 77, 58, 90, 30, 48, 32, 49, 80, 58, 65, 5, 24, 88, 27, 44, 15, 5, 65, 11, 14, 80, 30, 5, 23, 31, 38, 55, 1, 94, 15, 89, 69, 23, 35, 45, 38, 96, 11, 35, 22, 90, 46, 39, 69, 11, 26, 53, 18, 23, 8, 85, 22, 12, 49, 79, 63, 39, 1, 89, 68, 91, 24...
  1. Define a generator for Map[UUID, () => String].
val pairGen = for {
uuid <- Gen.uuid
function0 <- Gen.function0(Gen.asciiStr)
} yield (uuid, function0)

val mapGen = Gen.mapOf(pairGen)
mapGen: org.scalacheck.Gen[Map[java.util.UUID,() => String]] = org.scalacheck.Gen$$anon$1@16ca4e8d

scala> mapGen.sample
res36: Option[Map[java.util.UUID,() => String]] = Some(Map(31395a9b-78af-4f4a-9bf3-c19b3fb245b6 -> org.scalacheck.Gen$$$Lambda$2361/1400300928@178b18c, ...

Please note that Gen.function0 generates a function of zero arguments that just return random values generated by the provided generator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.178.151