scalacheck 中常规类的生成器
在scalacheck的用户指南中有“生成案例类”段落。我修改了它的示例以使用常规类而不是案例类:
import org.scalacheck._
import Gen._
import Arbitrary._
sealed abstract class Tree
object Leaf extends Tree
class Node(left:Tree, rigth:Tree, v:Int) extends Tree
object Main {
val genLeaf = value(Leaf)
val genNode = for{
v <- Arbitrary.arbitrary[Int]
left <- genTree
rigth <- genTree
} yield new Node(left, rigth, v)
val genTree:Gen[Tree] = oneOf(genLeaf, genNode)
def main(args:Array[String]){
println(genTree.sample)
}
}
看起来一切正常,但在我问这里之前,我担心在生产代码中使用这种方法:有任何陷阱吗?
In scalacheck's user guide there is "Generating Case Classes" paragraph. I modified example from it to use regular classes instead of case classes:
import org.scalacheck._
import Gen._
import Arbitrary._
sealed abstract class Tree
object Leaf extends Tree
class Node(left:Tree, rigth:Tree, v:Int) extends Tree
object Main {
val genLeaf = value(Leaf)
val genNode = for{
v <- Arbitrary.arbitrary[Int]
left <- genTree
rigth <- genTree
} yield new Node(left, rigth, v)
val genTree:Gen[Tree] = oneOf(genLeaf, genNode)
def main(args:Array[String]){
println(genTree.sample)
}
}
It seems everything working but I'm afraid of using this approach in production code before I ask here: is there any pitfalls?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该可以正常工作。就 ScalaCheck 而言,案例类并没有什么特别神奇的地方。任何旧类都可以获得生成器,甚至可以转换为任意类。
就测试而言,一个区别是您生成的每个非案例类树都是唯一的,因此您生成的两棵树都不会是tree1 == tree2。这与案例类的方式不同,案例类根据值而不是身份来测试相等性。您可能需要更多的测试来处理别名问题,当您具有基于身份而不是基于值的平等时,这些问题就可能出现。
This should work fine. There's nothing about case classes that are particularly magical about case classes as far as ScalaCheck is concerned. Any old class can get a generator, or even be convertible to Arbitrary.
As far as testing goes, one difference is that every non-case-class tree you generate will be unique, and thus for no two trees you generate will tree1 == tree2. That's different from how it is with case class, which test equality based on value rather than identity. You may need more tests to handle issues with aliasing that become possible when you have identity-based rather than value-based equality.
我看这里没有问题。在该示例中使用案例类的原因是,所示的
Tree
是一种代数数据类型,可以通过案例类实现。对于普通的类,您无法在树上进行模式匹配,事实上,您甚至无法获得left
、right
和v 而不声明它们
val
。I see no problem here. The reason why case classes are used in that example is that the
Tree
shown is an algebraic data type, made possible with case classes. With normal classes, you cannot pattern match on the tree, and, in fact, you won't even be able to getleft
,right
andv
without declaring themval
.