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

前端 未结 3 1333
甜味超标
甜味超标 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: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.

提交回复
热议问题