gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:06:27 27 4
gpt4 key购买 nike

如何使用类似于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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com