Convert List[Either[A, B]] to Either[List[A], List[B]]

前端 未结 3 1327
甜味超标
甜味超标 2021-01-12 09:49

How to convert List[Either[String, Int]] to Either[List[String], List[Int]] using a method similar to cats sequence? For example, xs.sequenc

相关标签:
3条回答
  • 2021-01-12 10:20

    This solution doesn't use cats, but from Scala 2.13, you can use of partitionMap:

        def convert[L,R](input: List[Either[L,R]]): Either[List[L], List[R]] = {
          val (left, right) = input.partitionMap(identity)
          if (left.isEmpty) Right(right) else Left(left)
        }
    
        println(convert(List(Left("error1"), Left("error2"))))
        // Left(List(error1, error2))
        println(convert(List(Right(1), Left("2"), Right(3), Left("4"))))
        // Left(List(2, 4))
        println(convert(List(Right(1), Right(2), Right(3), Right(4))))
        // Right(List(1, 2, 3, 4))
    
    0 讨论(0)
  • 2021-01-12 10:25

    Another variation on the same theme (similar to this answer), all imports included:

    import scala.util.Either
    import cats.data.Validated
    import cats.syntax.traverse._
    import cats.instances.list._
    
    def collectErrors[A, B](xs: List[Either[A, B]]): Either[List[A], List[B]] = {
      xs.traverse(x => Validated.fromEither(x.left.map(List(_)))).toEither
    }
    

    If you additionally import cats.syntax.either._, then the toValidated becomes available, so you can also write:

    xs.traverse(_.left.map(List(_)).toValidated).toEither
    

    and if you additionally replace the left.map by bimap(..., identity), you end up with @DmytroMitin's wonderfully concise solution.

    0 讨论(0)
  • 2021-01-12 10:35

    Try

    xs.traverse(_.toValidated.bimap(List(_), identity)).toEither
    
    // List(Left("error1"), Left("error2")) => Left(List("error1", "error2"))
    // List(Right(10), Right(20))           => Right(List(10, 20))
    // List(Right(10), Left("error2"))      => Left(List("error2"))
    
    0 讨论(0)
提交回复
热议问题