gpt4 book ai didi

ScalaCheck:生成任意类型的任意函数

转载 作者:行者123 更新时间:2023-12-01 09:45:31 26 4
gpt4 key购买 nike

我已经实现了以下功能:

/**
* Returns a function h , which is the composition of the functions f and g.
*/
def compose[A, B, C](g: B => C, f: A => B): A => C = f.andThen(g)

我正在尝试用 ScalaCheck 测试它.我可以生成以下测试,这些测试可以编译并通过:
import org.scalatest.prop.PropertyChecks
import org.scalatest.{FlatSpec, Matchers}

class ComposeSpec extends FlatSpec with Matchers with PropertyChecks {

"Compose" should "return a function h , which is the composition of the
functions f and g" in {

forAll { (a: Int, g: Int => Int, f: Int => Int) =>
compose(g, f)(a) should be(g(f(a)))
}

forAll { (a: String, g: Double => Int, f: String => Double) =>
compose(g, f)(a) should be(g(f(a)))
}
}
}

但是,如您所见,我正在生成具有定义类型的任意函数,并且还匹配参数 a 的类型与函数的输入类型 f .我想做的是这样的:
forAll { (a: A, g: B => C, f: A => B) =>
compose(g, f)(a) should be(g(f(a)))
}

但我不知道它的语法,也不知道它是否可能。你可以帮帮我吗?

最佳答案

scalatest website关于forAll有这个说法吗:

An implicit Arbitrary generator and Shrink object needs to be supplied for The forAll method will pass each row of data to each parameter type. ScalaCheck provides many implicit Arbitrary generators for common types such as Int, String, List[Float], etc., in its org.scalacheck.Arbitrary companion object. So long as you use types for which ScalaCheck already provides implicit Arbitrary generators, you needn't worry about them. Same for Shrink objects, which are provided by ScalaCheck's org.scalacheck.Shrink companion object. Most often you can simply pass a property function to forAll, and the compiler will grab the implicit values provided by ScalaCheck.



所以很遗憾你不能使用 forAll检查所有可能的类型,因为没有隐式 ArbitraryShrink每种可能类型的对象。生成任何类型的任意对象似乎是不可能的。

你能做的最好的事情是:
def checkComposeForAll[A : Arbitrary : Shrink, B : Arbitrary : Shrink, C : Arbitrary : Shrink]() = {
forAll { (a: A, g: B => C, f: A => B) =>
compose(g, f)(a) should be(g(f(a)))
}
}

checkComposeForAll[Int, Int, Int]()
checkComposeForAll[String, String, String]()
checkComposeForAll[List[Int], Double, Int]()
// ... etc, check a bunch of types ...

关于ScalaCheck:生成任意类型的任意函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50412055/

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