作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何使用类似于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))
。
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/
我是一名优秀的程序员,十分优秀!