1

我正在尝试生成一个任意列表,如下所示:

scala> def validPairs[T] = Arbitrary.arbitrary[List[(T, Option[T])]] suchThat(!_.isEmpty)
<console>:8: error: could not find implicit value for parameter a: org.scalacheck.Arbitrary[List[(T, Option[T])]]
   def validPairs[T] = Arbitrary.arbitrary[List[(T, Option[T])]] suchThat(!_.isEmpty)

知道我在这里做错了什么吗?使用具体类型无需我定义隐式参数即可。

scala> def validPairsString = Arbitrary.arbitrary[List[(String, Option[String])]] suchThat(!_.isEmpty)
validPairsString: org.scalacheck.Gen[List[(String, Option[String])]]

这是使用 scala 2.9.2 和 scalacheck 1.10.0

提前致谢。

4

2 回答 2

2

I have hit this problem myself, trying to generate generic properties, that can later be instantiated for various concrete types. I found the OP's answer a bit crytpic, so I thought it would be good to provide a more elaborate one. I first repeat OP's answer slowly. Then show that the same applies to writing properties with scalacheck.

The key problem is that the following does not compile (I simplified the problem given by the OP):

def validPair[T] = Arbitrary.arbitrary[(T,T)]

With a modern Scala compiler you get a different error message:

diverging implicit expansion for type org.scalacheck.Arbitrary[(T, T)]
starting with method arbTuple2 in trait ArbitraryArities

(this to help those who Google for this problem today).

It suffices to bound the type parameter by arbitrary (the OP's answer was a bit cryptic on quick reading):

def validPair[T :Arbitrary] = Arbitrary.arbitrary[(T,T)]

Now the same needs to be done if you are defining generic properties. Here is an example of associativity axiom for monoids:

def associative[A :Arbitrary] (m: Monoid[A]) :Prop =
  forAll ( (a1: A, a2: A, a3: A) => m.op(m.op(a1,a2), a3) == m.op(a1,m.op(a2,a3)) )

It yields a similar error without the bound of A to Arbitrary. I hope others starting to write their first generic properties with scalacheck will find this useful.

于 2015-09-14T14:58:40.803 回答
1

在不同的列表中找到答案:def validPairs[T : Arbitrary] = ...(告诉它您将提供一种(可能是隐式的)生成 T 的方式。)

于 2013-05-15T16:59:41.323 回答