简体   繁体   中英

Scalaz: Map of ValidationNel to ValidationNel of Map

How do I convert a

val source: Map[MyKeyType, ValidationNel[MyErrorType, MyValueType]]

to

val target: ValidationNel[MyErrorType, Map[MyKeyType, MyValueType]]

while capturing all validation errors?

You can use sequence to turn a type F[G[A]] inside out (ie, into a G[F[A]] ) if you have two things: an Applicative instance for G and a Traverse instance for F . In this case Scalaz provides both off the shelf, so you can just write source.sequenceU (where the U part indicates that this is a method that uses the Unapply trick to help out Scala's type inference system).

For example:

scala> println(Map("a" -> 1.successNel, "b" -> 2.successNel).sequenceU)
Success(Map(a -> 1, b -> 2))

scala> println(Map("a" -> 1.successNel, "b" -> "BAD".failureNel).sequenceU)
Failure(NonEmptyList(BAD))

And errors will be accumulated as expected.

你想要sequenceU

val target = source.sequenceU

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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