1

我创建了一个类似于 Play JsonReads[T]类型的 Monad 类型,称为ReadYamlValue.

trait ReadYamlValue[T] {
  def read(json: YamlValue): ReadResult[T]
  // ... methods include map, flatMap, etc
}

我为此创建了一个 catMonad实例:

implicit val ReadYamlValueMonad: Monad[ReadYamlValue] = new Monad[ReadYamlValue] {
  override def flatMap[A, B](fa: ReadYamlValue[A])(f: A => ReadYamlValue[B]): ReadYamlValue[B] = {
    fa flatMap f
  }
  override def tailRecM[A, B](a: A)(f: A => ReadYamlValue[Either[A, B]]): ReadYamlValue[B] = {
    ReadYamlValue.read[B] { yaml =>
      @tailrec def readB(reader: ReadYamlValue[Either[A, B]]): ReadResult[B] = {
        reader.read(yaml) match {
          case Good(Left(nextA)) => readB(f(nextA))
          case Good(Right(b)) => Good(b)
          case Bad(error) => Bad(error)
        }
      }
      readB(f(a))
    }
  }
  override def pure[A](x: A): ReadYamlValue[A] = ReadYamlValue.success(x)
}

然后我想用MonadLawsScalaCheck 来测试它。

class CatsTests extends FreeSpec with discipline.MonadTests[ReadYamlValue] {
  monad[Int, Int, Int].all.check()
}

但我得到:

could not find implicit value for parameter EqFA: cats.Eq[io.gloriousfuture.yaml.ReadYamlValue[Int]]

我如何定义Eq什么是有效的功能?比较函数的相等性似乎不是我想要的......我的ReadYamlValue类不是 Monad 甚至是 Functor 吗?

一种方法是生成任意样本并比较结果的相等性:

implicit def eqReadYaml[T: Eq: FormatYamlValue: Arbitrary]: Eq[ReadYamlValue[T]] = {
  Eq.instance { (a, b) =>
    val badYaml = arbitrary[YamlValue].getOrThrow
    val goodValue = arbitrary[T].getOrThrow
    val goodYaml = Yaml.write(goodValue)
    Seq(badYaml, goodYaml).forall { yaml =>
      (a.read(yaml), b.read(yaml)) match {
        case (Good(av), Good(bv)) => Eq.eqv(av, bv)
        case (Bad(ae), Bad(be)) => Eq.eqv(ae, be)
        case _ => false
      }
    }
  }
}

但这似乎有点回避平等的定义。有没有更好或更规范的方法来做到这一点?

4

1 回答 1

1

看起来使用 Arbitrary 实例是 Circe 的做法:

https://github.com/travisbrown/circe/blob/master/modules/testing/shared/src/main/scala/io/circe/testing/EqInstances.scala

他们采用 16 个样本流并比较结果。

于 2016-10-26T15:38:57.223 回答