Search code examples
scalascalacheckhigher-kinded-types

Scalacheck issue with higher kinds : diverging implicit expansion for type Arbitrary


I've defined a monad type class and I'm trying to verify its law with scalacheck.

I have the following error :

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

My scalacheck code is the following :

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)
    }
  }
}

Did I miss soemthing in the implicit Arbitrary types ?

Here is my 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)
  }
}

Thanks


Solution

  • You have an implicit Arbitrary[Box[A]] in scope, but you don't have one for Arbitrary[Box[B]] (which Scalacheck needs to create one for A => Box[B]) or for Arbitrary[Box[C]] (which it'll ask for afterwards).

    A more principled approach would be to create something like

    trait Arbitrary1[F[_]] {
      def liftArb[A](arb: Arbitrary[A]): Arbitrary[F[A]]
    }
    

    and provide Arbitrary1[Box] but it would require being more explicit when calling forAll.