通过mapN验证的猫

时间:2019-02-11 17:18:49

标签: scala scala-cats

我是Cats的初学者。 验证猫出现错误。我使用这样的列表累加器:

case class Type(
 name: String,
 pattern: String,
 primitiveType: PrimitiveType = PrimitiveType.string,
 sample: Option[String] = None,
 comment: Option[String] = None,
 stat: Option[Stat] = None
) {
 type ValidationResult[A] = Validated[List[String], A]

 def checkValidity(): ValidationResult[Boolean] = {
  val errorList: mutable.MutableList[String] = mutable.MutableList.empty

  val patternIsValid = Try {
   primitiveType match {
    case PrimitiveType.struct =>
    case PrimitiveType.date =>
      new SimpleDateFormat(pattern)
    case PrimitiveType.timestamp =>
      pattern match {
        case "epoch_second" | "epoch_milli" =>
        case _ if PrimitiveType.formatters.keys.toList.contains(pattern) =>
        case _ =>
          DateTimeFormatter.ofPattern(pattern)
      }
    case _ =>
      Pattern.compile(pattern)
   }
 }
 if (patternIsValid.isFailure)
  errorList += s"Invalid Pattern $pattern in type $name"
 val ok = sample.forall(this.matches)
 if (!ok)
  errorList += s"Sample $sample does not match pattern $pattern in type $name"
 if (errorList.nonEmpty)
  Invalid(errorList.toList)
 else
  Valid(true)
}
}

在我的案例类Types中使用此功能时:

case class Types(types: List[Type]) {

 type ValidationResult[A] = Validated[List[String], A]

 def checkValidity(): ValidationResult[Boolean] = {
   val typeNames = types.map(_.name)
   val dup: ValidationResult[Boolean] =
   duplicates(typeNames, s"%s is defined %d times. A type can only be defined once.")
  (dup,types.map(_.checkValidity()).sequence).mapN((_,_) => true)
 }
}

我遇到此错误

Error:(29, 39) Cannot prove that cats.data.Validated[List[String],Boolean] <:< G[A].
(dup,types.map(_.checkValidity()).sequence: _*).mapN((_,_) => true)

您能帮我解决此错误吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:8)

很多年前,如果您对历史或一些旧的解决方法感兴趣,我就在这里遇到的潜在问题写了long blog post,但幸运的是,现在的解决方案要容易得多(假设您(在Scala 2.11或2.12上):只需将-Ypartial-unification添加到您的Scala编译器选项中即可。例如,如果您使用的是sbt,则可能看起来像这样:

scalacOptions += "-Ypartial-unification"

您完成了。

如果由于某种原因而无法添加编译器选项,则必须显式提供一些类型参数。这是一个快速的简化版本:

import cats.data.Validated, cats.implicits._


case class Foo(i: Int) {
  type ValidationResult[A] = Validated[List[String], A]

  def check: ValidationResult[Boolean] =
    if (i < 0) Validated.invalid(List("bad")) else Validated.valid(true)
}

case class Foos(values: List[Foo]) {
  type ValidationResult[A] = Validated[List[String], A]

  def dup: ValidationResult[Unit] = Validated.valid(())
  def check: ValidationResult[Boolean] =
    (dup, values.map(_.check).sequence).mapN((_, _) => true)
}

这将因您看到的错误而失败(假设您尚未添加-Ypartial-unification):

<console>:22: error: Cannot prove that cats.data.Validated[List[String],Boolean] <:< G[A].
           (dup, values.map(_.check).sequence).mapN((_, _) => true)
                                     ^

要解决此问题,您可以编写以下内容:

case class Foos(values: List[Foo]) {
  type ValidationResult[A] = Validated[List[String], A]

  def dup: ValidationResult[Unit] = Validated.valid(())
  def check: ValidationResult[Boolean] =
    (dup, values.map(_.check).sequence[ValidationResult, Boolean]).mapN((_, _) => true)
}

我认为您也可以将类型别名移到程序包级别,但是对此我不是100%肯定,也不愿意检查。

一个脚注:每当您拥有map然后是sequence时,都可以使用traverse来使事情变得更快一些:

  def check: ValidationResult[Boolean] =
    (dup, values.traverse[ValidationResult, Boolean](_.check)).mapN((_, _) => true)

同样,如果启用了-Ypartial-unification,则可以删除类型参数,并让类型推断将其找出来。