scalacheck 中常规类的生成器

发布于 2024-09-17 16:56:34 字数 711 浏览 1 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒儿 2024-09-24 16:56:34

这应该可以正常工作。就 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.

千年*琉璃梦 2024-09-24 16:56:34

我看这里没有问题。在该示例中使用案例类的原因是,所示的 Tree 是一种代数数据类型,可以通过案例类实现。对于普通的类,您无法在树上进行模式匹配,事实上,您甚至无法获得 leftrightv 而不声明它们 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 get left, right and v without declaring them val.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文