Scalaz: ValidationNel Map for ValidationNel of Map

How to convert

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

      

to

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

      

while capturing all validation errors?

+3


source to share


2 answers


You can use sequence

to rotate a type F[G[A]]

from inside (i.e. to G[F[A]]

) if you have two things: an instance Applicative

for G

and an Traverse

instance for F

. In this case, Scalaz provides both off the shelf, so you can just write source.sequenceU

(where the part U

indicates that this is a method that uses a trick Unapply

to help in 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 pile up as expected.

+3


source


You want sequenceU

:



val target = source.sequenceU

      

+2


source







All Articles