ScalaCheck:权威指南解释了如何为递归数据结构创建生成器。
首先,它定义了数据结构:
trait Tree[T] {
def size: Int
}
case class Leaf[T](item: T) extends Tree[T] {
def size = 1
}
case class Node[T] (children: List[Tree[T]]) extends Tree[T] {
def size = children.map(_.size).sum
}
接下来,它显示Gen[Tree[A]]
代码:
import org.scalacheck.Gen
import org.scalacheck.Gen.{oneOf, listOf, lzy}
def genTree[T](genT: Gen[T]): Gen[Tree[T]] = lzy {
oneOf(genLeaf(genT), genNode(genT))
}
def genLeaf[T](genT: Gen[T]): Gen[Leaf[T]] =
genT.map(Leaf(_))
def genNode[T](genT: Gen[T]): Gen[Node[T]] = for {
children <listOf(
genTree(genT))
} yield Node(children)
对于上面的生成器,本书演示了,调用它可能会导致StackOverflowError
:
scala> genIntTree.sample
res0: Option[Tree[Int]] = Some(Leaf(2147483648))
scala> genIntTree.sample
res1: Option[Tree[Int]] = Some(Leaf(0))
scala> genIntTree.sample
java.lang.StackOverflowError
at org.scalacheck.Gen$$anonfun$1$$anonfun$apply...
给定以下MyList
数据结构:
sealed abstract class MyList[+A]
case class Cons[+A](elem: A, rest: MyList[A]) extends MyList[A]
case object Empty extends MyList[Nothing]
以及以下生成器:
def genList[A](gen: Gen[A]): Gen[MyList[A]] =
lzy { oneOf(genCons(gen), Gen.const(Empty)) }
def genCons[A](gen: Gen[A]): Gen[MyList[A]] = for {
list <- genList(gen)
a <- gen
} yield Cons(a, list)
我的理解是,Gen[Tree[A]]
对 的使用listOf
负责StackOverflowError
。
但是,代码StackOverflowError
生成器中是否有可能Gen[MyList[A]]
?
我猜是如果足够genList
返回足够Cons
的,但我不确定。