如何转换List[Either[String, Int]]为Either[List[String], List[Int]]使用类似于cats sequence的方法?例如, xs.sequence在以下代码中
import cats.implicits._
val xs: List[Either[String, Int]] = List(Left("error1"), Left("error2"))
xs.sequence
Run Code Online (Sandbox Code Playgroud)
返回,Left(error1)而不是required Left(List(error1, error2))。
凯文·赖特的答案表明
val lefts = xs collect {case Left(x) => x }
def rights = xs collect {case Right(x) => x}
if(lefts.isEmpty) Right(rights) else Left(lefts)
Run Code Online (Sandbox Code Playgroud)
哪个返回Left(List(error1, error2)),但是猫是否提供开箱即用的排序方式来收集所有剩余数据?
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
}
Run Code Online (Sandbox Code Playgroud)
If you additionally import cats.syntax.either._, then the toValidated becomes available, so you can also write:
xs.traverse(_.left.map(List(_)).toValidated).toEither
Run Code Online (Sandbox Code Playgroud)
and if you additionally replace the left.map by bimap(..., identity), you end up with @DmytroMitin's wonderfully concise solution.