scalacheck项目的UserGuide提到了大小生成器。解释码

def matrix[T](g:Gen[T]):Gen[Seq[Seq[T]]] = Gen.sized {size =>
 val side = scala.Math.sqrt(size).asInstanceOf[Int] //little change to prevent compile-time exception
 Gen.vectorOf(side, Gen.vectorOf(side, g))
}


没有为我解释什么。经过一番探索,我了解到所生成序列的长度并不取决于生成器的实际大小(Gen对象中有一个resize方法,根据javadoc,它“创建了生成器的调整大小的版本”(也许意味着不同吗?))。

val g =  Gen.choose(1,5)
val g2 = Gen.resize(15, g)
println(matrix(g).sample) //  (1)
println(matrix(g2).sample) // (2)
//1,2 produce Seq with same length


您能否解释一下我错过了什么,并举一些例子说明如何在测试代码中使用它们?

最佳答案

不建议使用您使用的vectorOf方法,而应使用listOf方法。这将生成一个随机长度列表,其中最大长度受生成器大小限制。因此,您应该调整生成器的大小,以便
如果要控制所生成的最大元素,则实际生成实际列表:


scala> val g1 = Gen.choose(1,5)
g1: org.scalacheck.Gen[Int] = Gen()

scala> val g2 = Gen.listOf(g1)
g2: org.scalacheck.Gen[List[Int]] = Gen()

scala> g2.sample
res19: Option[List[Int]] = Some(List(4, 4, 4, 4, 2, 4, 2, 3, 5, 1, 1, 1, 4, 4, 1, 1, 4, 5, 5, 4, 3, 3, 4, 1, 3, 2, 2, 4, 3, 4, 3, 3, 4, 3, 2, 3, 1, 1, 3, 2, 5, 1, 5, 5, 1, 5, 5, 5, 5, 3, 2, 3, 1, 4, 3, 1, 4, 2, 1, 3, 4, 4, 1, 4, 1, 1, 4, 2, 1, 2, 4, 4, 2, 1, 5, 3, 5, 3, 4, 2, 1, 4, 3, 2, 1, 1, 1, 4, 3, 2, 2))

scala> val g3 = Gen.resize(10, g2)
g3: java.lang.Object with org.scalacheck.Gen[List[Int]] = Gen()

scala> g3.sample
res0: Option[List[Int]] = Some(List(1))

scala> g3.sample
res1: Option[List[Int]] = Some(List(4, 2))

scala> g3.sample
res2: Option[List[Int]] = Some(List(2, 1, 2, 4, 5, 4, 2, 5, 3))

关于scala - Scalacheck中的大型发电机,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3666744/

10-12 06:16