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

≡放荡痞女 提交于 2019-12-01 01:13:52

问题


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

import cats.implicits._
val xs: List[Either[String, Int]] = List(Left("error1"), Left("error2"))
xs.sequence

returns Left(error1) instead of required Left(List(error1, error2)).

KevinWrights' answer suggests

val lefts = xs collect {case Left(x) => x }
def rights = xs collect {case Right(x) => x}
if(lefts.isEmpty) Right(rights) else Left(lefts)

which does return Left(List(error1, error2)), however does cats provide out-of-the-box sequencing which would collect all the lefts?


回答1:


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.




回答2:


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))



回答3:


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"))



回答4:


Note: this answer assumes you want to get a Left as soon as a single element in the list is one.

You could use .separate() to split the list to a tuple (List[String], List[Int]) and match over that:

scala> xs.separate match {
          case (Nil, rights) => Right(rights)
          case (lefts, _)    => Left(lefts)
       }
res0: scala.util.Either[List[String],List[Int]] = Left(List(error1, error2))

Not 'out-of-the-box' as you still need the match, but still pretty short (and hopefully easy to understand).



来源:https://stackoverflow.com/questions/56501107/convert-listeithera-b-to-eitherlista-listb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!