更高类型的Scalacheck问题:类型Arbitrary的隐式扩展分歧

时间:2017-12-11 08:23:20

标签: scala scalacheck higher-kinded-types

我已经定义了一个monad类型的类,我正试图用scalacheck验证它的定律。

我有以下错误:

diverging implicit expansion for type org.scalacheck.Arbitrary[(A, Box[B])]

我的scalacheck代码如下:

class OptionMonadSpec extends MonadSpec[String, String, String, Option](Monad.optionMonad)

abstract class MonadSpec[A, B, C, Box[_] : ClassTag](monad: Monad[Box])
(implicit boxArb: Arbitrary[Box[A]], aArb: Arbitrary[A], bArb: Arbitrary[B], cArb: Arbitrary[C])
  extends Properties(s"Monad for ${classTag[Box[_]]}") {
  property("left identity") = forAll { (f: (A => Box[B]), a: A) =>
    val boxA: Box[A] = monad.pure(a)
    monad.flatMap(boxA)(f) == f(a)
  }
  property("right identity") = forAll { box: Box[A] =>
    monad.flatMap(box)(monad.pure) == monad
  }
  property("associativity") = forAll { (f: (A => Box[B]), g: (B => Box[C]), box: Box[A]) =>
    val boxB: Box[B] = monad.flatMap(box)(f)
    monad.flatMap(boxB)(g) == monad.flatMap(box) { a =>
      val boxB: Box[B] = f(a)
      monad.flatMap(boxB)(g)
    }
  }
}

我是否在隐含的任意类型中错过了soemthing?

这是我的monad:

trait Monad[Box[_]] extends Functor[Box] {

  def pure[A](a: A): Box[A]

  def flatMap[A, B](boxA: Box[A])(f: A => Box[B]): Box[B]

}

object Monad {

  implicit val optionMonad = new Monad[Option] {

    override def pure[A](x: A): Option[A] = Some(x)

    override def flatMap[A, B](boxA: Option[A])(f: A => Option[B]) = boxA.flatMap(f)

    override def map[A, B](boxA: Option[A])(f: A => B) = boxA.map(f)
  }
}

由于

1 个答案:

答案 0 :(得分:3)

您在范围内有一个隐式Arbitrary[Box[A]],但您没有Arbitrary[Box[B]](Scalacheck需要为A => Box[B]创建一个)或Arbitrary[Box[C]](之后它会要求的)。

更有原则的方法是创建像

这样的东西
trait Arbitrary1[F[_]] {
  def liftArb[A](arb: Arbitrary[A]): Arbitrary[F[A]]
}

并提供Arbitrary1[Box],但在调用forAll时需要更明确。