gpt4 book ai didi

Scalacheck 收缩

转载 作者:行者123 更新时间:2023-12-04 15:19:11 37 4
gpt4 key购买 nike

我对 ScalaCheck(以及整个 Scala)相当陌生,所以这可能是一个相当简单的解决方案

我正在使用 ScalaCheck 为 AST 生成测试并验证编写器/解析器是否工作。我有这些文件

AST.scala

package com.test

object Operator extends Enumeration {
val Add, Subtract, Multiply, Divide = Value
}

sealed trait AST
case class Operation(left: AST, op: Operator.Value, right: AST) extends AST
case class Literal(value: Int) extends AST

GenOperation.scala
import com.test.{AST, Literal}

import org.scalacheck._
import Shrink._
import Prop._
import Arbitrary.arbitrary

object GenLiteral extends Properties("AST::Literal") {
property("Verify parse/write") = forAll(genLiteral){ (node) =>
// val string_version = node.writeToString() // AST -> String
// val result = Parse(string_version) // String -> AST
true
}

def genLiteral: Gen[Literal] = for {
value <- arbitrary[Int]
} yield Literal(value)

implicit def shrinkLiteral: Shrink[AST] = Shrink {
case Literal(value) =>
for {
reduced <- shrink(value)
} yield Literal(reduced)
}
}

GenOperation.scala
import com.test.{AST, Operation}

import org.scalacheck._
import Gen._
import Shrink._
import Prop._

import GenLiteral._

object GenOperation extends Properties("AST::Operation") {
property("Verify parse/write") = forAll(genOperation){ (node) =>
// val string_version = node.writeToString() // AST -> String
// val result = Parse(string_version) // String -> AST
true
}

def genOperation: Gen[Operation] = for {
left <- oneOf(genOperation, genLiteral)
right <- oneOf(genOperation, genLiteral)
op <- oneOf(Operator.values.toSeq)
} yield Operation(left,op,right)

implicit def shrinkOperation: Shrink[AST] = Shrink {
case Operation(l,o,r) =>
(
for {
ls <- shrink(l)
rs <- shrink(r)
} yield Operation(ls, o, rs)
) append (
for {
ls <- shrink(l)
} yield Operation(ls, o, r)
) append (
for {
rs <- shrink(r)
} yield Operation(l, o, rs)
) append shrink(l) append shrink(r)
}

}

在我写的示例代码(上面粘贴的内容)中,我收到错误
ambiguous implicit values:
both method shrinkLiteral in object GenLiteral of type => org.scalacheck.Shrink[com.test.AST]
and method shrinkOperation in object GenOperation of type => org.scalacheck.Shrink[com.test.AST]
match expected type org.scalacheck.Shrink[com.test.AST]
ls <- shrink(l)

我如何为此编写收缩方法?

最佳答案

您有两个 Shrink[AST] 的隐式实例因此编译器会提示不明确的隐式值。

您可以将代码重写为:

implicit def shrinkLiteral: Shrink[Literal] = Shrink {
case Literal(value) => shrink(value).map(Literal)
}

implicit def shrinkOperation: Shrink[Operation] = Shrink {
case Operation(l,o,r) =>
shrink(l).map(Operation(_, o, r)) append
shrink(r).map(Operation(l, o, _)) append ???
}

implicit def shrinkAST: Shrink[AST] = Shrink {
case o: Operation => shrink(o)
case l: Literal => shrink(l)
}

关于Scalacheck 收缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42581883/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com