Applying validation from HList to case class

When trying to do validation using application functors ( Monad to catch a few exceptions (not just crashing on one) ), I came across a hard limit in scalaz that forbids more than 14 functors, so a useful comment here ( https://github.com / scalaz / scalaz / issues / 504 # issuecomment-23626237 ) moved me to use HLists instead of applicative functors

Now it works fine (after it is manually placed in this sequence file, since it is not in maven https://github.com/typelevel/shapeless-contrib/blob/master/scalaz/main/scala/sequence.scala ? source = c )

My question is, and I know that it is possible, how would you do an automatic instance creation of a case class Foo(i:Int,s:String) without having to manually map the template to the case, just to reapply the parameters again

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) } } 
+4
source share
1 answer

First for the lowest point: the type parameter for successNel is the type of error, not the type of success, so it should be the same for all sequence arguments.

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 the validation. 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 use the Foo constructor manually.

+7
source

Source: https://habr.com/ru/post/1500064/


All Articles