scala - 将列表[Either[A, B]] 转换为Either[List[A], List[B]]

标签 scala scala-cats

如何使用类似于cats sequence 的方法将List[Either[String, Int]] 转换为Either[List[String], List[Int]]?比如下面代码中的xs.sequence

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

返回 Left(error1) 而不是必需的 Left(List(error1, error2))

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

这确实返回 Left(List(error1, error2)) ,但是猫是否提供开箱即用的排序来收集所有左边?

最佳答案

同一主题的另一个变体(类似于 this answer ),所有进口包括:

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
}

如果您另外导入 cats.syntax.either._ ,然后是 toValidated变得可用,所以你也可以写:
xs.traverse(_.left.map(List(_)).toValidated).toEither

如果您另外更换 left.map来自 bimap(..., identity) ,您最终会得到@DmytroMitin 非常简洁的解决方案。

关于scala - 将列表[Either[A, B]] 转换为Either[List[A], List[B]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56501107/

相关文章:

scala - 如何让IntelliJ scala项目使用Scala 2.9.2版本?

sql - Spark DataFrame中=== null和isNull之间的区别

json - 通过circe修改json字段类型

scala - 将 'A => F[G[B]]' 转换为 'F[G[A=>B]' scala

scala - Spark 中的性能调整

scala - Scala 中的一个奇怪的 NullPointerException

scala - 类型构造函数参数推断

scala - flatMap 忽略结果

scala - 如何使用Foldable的foldM?

scala - 如何使用 Monoid Scala?