gpt4 book ai didi

scala - 将 List[Either[A, B]] 平铺到 List[B],就像 List[Option[B]] 平铺到 List[B]

转载 作者:行者123 更新时间:2023-12-03 05:12:22 26 4
gpt4 key购买 nike

猫是否提供类似的扁平化

implicit class FlattenListOfEither[L, R](l: List[Either[L, R]]) {
def flattenM: List[R] = l collect { case Right(v) => v }
}

这样

val l1: List[Either[String, Int]] = List(Right(1), Right(2), Left("error"), Right(4))
l1.flattenM

输出

List(1, 2, 4)

类似于普通 Scala 如何展平选项列表

val l2: List[Option[Int]] = List(Some(1), Some(2), None, Some(4))
l2.flatten

输出

List(1, 2, 4)

separate给出以下语法

import cats.implicits._
val (_, rights) = l1.separate
rights

输出

List(1, 2, 4)

但是,是否存在开箱即用的类似 flatten 的扩展方法,它只返回权限而不是元组?

最佳答案

我认为最简单的是使用 FunctorFilter 类型类提供的 mapFilter 。它看起来像这样:

def mapFilter[A, B](fa: F[A])(f: (A) ⇒ Option[B]): F[B]

其中 F[A] 可以是 List[A]Vector[A] 或任何其他允许过滤的类型。

如果我们将此函数应用于您的列表,我们只需将 Either[A, B] 转换为 Option[B] 即可。这就像调用 toOption 一样简单。完整的解决方案如下所示:

import cats.implicits._

val l1: List[Either[String, Int]] = List(Right(1), Right(2), Left("error"), Right(4))

l1.mapFilter(_.toOption)
// List(1, 2, 4)

关于scala - 将 List[Either[A, B]] 平铺到 List[B],就像 List[Option[B]] 平铺到 List[B],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57299794/

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