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 に答える