简体   繁体   English

将验证从HList应用于案例类

[英]Applying validation from HList to a case class

In attempting to do validation with application functors ( Monad to catch multiple exceptions (not just fail on single) ), I came across a hard limit in scalaz that disallows more than 14 functors, so a helpful comment from here ( https://github.com/scalaz/scalaz/issues/504#issuecomment-23626237 ) navigated me to use HLists instead of applicative functors 在尝试使用应用程序仿函数进行验证时( Monad捕获多个异常(不仅仅是单个失败) ),我在scalaz中遇到了一个禁止超过14个仿函数的硬限制,所以这里有一个有用的注释( https:// github .com / scalaz / scalaz / issues / 504#issuecomment-23626237 )导航我使用HLists而不是applicative functor

Now it works perfectly fine (after having to manually put in this sequence file from here since its not in maven https://github.com/typelevel/shapeless-contrib/blob/master/scalaz/main/scala/sequence.scala?source=c ) 现在它工作得非常好(从此处手动输入此序列文件,因为它不在maven https://github.com/typelevel/shapeless-contrib/blob/master/scalaz/main/scala/sequence.scala?来源= c

My question is, and I know this is possible, how would you go about automatically instantiating the case class Foo(i:Int,s:String) without having to manually match the pattern with a case, only to just reapply the parameters again 我的问题是,我知道这是可能的,你将如何自动实例化case class Foo(i:Int,s:String)而无需手动将模式与案例匹配,只是再次重新应用参数

Essentially I want to do something like this 基本上我想做这样的事情

  case class Foo(i:Int,s:String)

  implicit def TwoFoo = Iso.hlist(Foo.apply _, Foo.unapply _)

  val someFoo = sequence(
      1.successNel[Int] ::
      "2".successNel[String] ::
      HNil
  ).map { Foo.apply _} // Note this doesn't work

  someFoo match {
    case Success(a) => println(a)
    case Failure(a) => {
      println("failure")
      println(a)
    }
  }

First for a minor point: the type parameter for successNel is the error type, not the success type, so it needs to be the same across all the arguments to sequence . 首先是一个小问题: successNel的类型参数是错误类型,而不是成功类型,因此它需要在所有要sequence的参数中相同。

So we can write the following (assuming our errors are strings): 所以我们可以编写以下内容(假设我们的错误是字符串):

import shapeless._, contrib.scalaz._
import scalaz._, syntax.validation._

case class Foo(i: Int, s: String)

implicit val fooIso = Iso.hlist(Foo.apply _, Foo.unapply _)

val valHList = sequence(1.successNel[String] :: "2".successNel[String] :: HNil)

This gives us an Int :: String :: HNil inside a validation. 这给了我们验证中的Int :: String :: HNil Now we can use our isomorphism: 现在我们可以使用我们的同构:

scala> valHList.map(fooIso.from)
res0: scalaz.Validation[scalaz.NonEmptyList[String],Foo] = Success(Foo(1,2))

No need to deconstruct the list and apply the Foo constructor manually. 无需解构列表并手动应用Foo构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM