5

Let's say I have:

val x1: Either[String, Int] = Right(1)
val x2: Either[String, Float] = Left("Nope")
val x3: Either[String, Double] = Left("Not Today")

I want to combine these together and get a Either[NonEmptyList[String], (Int, Float, Double)]. To do this, I am currently doing the following:

import cats.syntax.all._
(
  x1.toValidatedNel,
  x2.toValidatedNel,
  x3.toValidatedNel
).tupled
 .toEither

Which does the job but is a bit tedious. Is there a way of doing this by calling toValidatedNel only once? something like:

(x1, x2, x3)
  .fooMap(_.toValidatedNel)
  .tupled
  .toEither

Does such a fooMap exist somewhere in cats? or do we need HLists for that?

Maths noob
  • 1,684
  • 20
  • 42

1 Answers1

3

Using Shapeless, it's

import shapeless.syntax.std.tuple._
object toValidatedNel extends Poly1 {
  implicit def cse[A, B, AA >: A]: Case.Aux[Either[A, B], ValidatedNel[AA, B]] = at(_.toValidatedNel[AA])
}

(x1, x2, x3)
  .map(toValidatedNel)
  .tupled
  .toEither
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66