我有一些如下代码,其中有一个列表,我想将其转换为列表中的一个。 特别是(在这种情况下),如果列表中有任何 Left,那么我返回它们列表的 Left,否则我返回权利列表的 Right。
val maybe: List[Either[String, Int]] = getMaybe
val (strings, ints) = maybe.partition(_.isLeft)
strings.map(_.left.get) match {
case Nil => Right(ints.map(_.right.get))
case stringList => Left(stringList)
}
打电话给
get
总是让我觉得我一定错过了什么。
有更惯用的方法吗?
data.partition(_.isLeft) match {
case (Nil, ints) => Right(for(Right(i) <- ints) yield i)
case (strings, _) => Left(for(Left(s) <- strings) yield s)
}
对于一张通行证:
data.partition(_.isLeft) match {
case (Nil, ints) => Right(for(Right(i) <- ints.view) yield i)
case (strings, _) => Left(for(Left(s) <- strings.view) yield s)
}
从
Scala 2.13
开始,大多数集合现在都提供了 partitionMap
方法,该方法根据返回 Right
或 Left
的函数对元素进行分区。
在我们的例子中,我们甚至不需要一个将输入转换为
Right
或 Left
的函数来定义分区,因为我们已经有了 Right
和 Left
。因此,可以简单地使用 identity
!
然后,只需根据是否有左项来匹配生成的左项和右项的分区元组即可:
eithers.partitionMap(identity) match {
case (Nil, rights) => Right(rights)
case (lefts, _) => Left(lefts)
}
// * List[Either[String, Int]] = List(Right(3), Left("error x"), Right(7))
// => Either[List[String],List[Int]] = Left(List(error x))
// * List[Either[String, Int]] = List(Right(3), Right(7))
// => Either[List[String],List[Int]] = Right(List(3, 7))
为了理解
partitionMap
,这里是中间步骤的结果:
List(Right(3), Left("error x"), Right(7)).partitionMap(identity)
// (List[String], List[Int]) = (List(error x), List(3, 7))
来自 Scala 书中的函数式编程的解决方案。
def sequence[E,A](es: List[Either[E,A]]): Either[E,List[A]] =
traverse(es)(x => x)
def traverse[E,A,B](es: List[A])(f: A => Either[E, B]): Either[E, List[B]] =
es match {
case Nil => Right(Nil)
case h::t => (f(h) map2 traverse(t)(f))(_ :: _)
}
def map2[EE >: E, B, C](a: Either[E, A], b: Either[EE, B])(f: (A, B) => C):
Either[EE, C] = for { a1 <- a; b1 <- b } yield f(a1,b1)
val list = List(Left("x"),Right(2), Right(4))
val strings = for (Left(x) <- list) yield(x)
val result = if (strings.isEmpty) Right(for (Right(x) <- list) yield(x))
else Left(strings)
您可以编写
split
的通用版本,如下所示:
def split[X, CC[X] <: Traversable[X], A, B](l : CC[Either[A, B]])
(implicit bfa : CanBuildFrom[Nothing, A, CC[A]], bfb : CanBuildFrom[Nothing, B, CC[B]]) : (CC[A], CC[B]) = {
def as = {
val bf = bfa()
bf ++= (l collect { case Left(x) => x})
bf.result
}
def bs = {
val bf = bfb()
bf ++= (l collect { case Right(x) => x})
bf.result
}
(as, bs)
}
这样:
scala> List(Left("x"),Right(2), Right(4)) : List[Either[java.lang.String,Int]]
res11: List[Either[java.lang.String,Int]] = List(Left(x), Right(2), Right(4))
scala> split(res11)
res12: (List[java.lang.String], List[Int]) = (List(x),List(2, 4))
scala> Set(Left("x"),Right(2), Right(4)) : Set[Either[java.lang.String,Int]]
res13: Set[Either[java.lang.String,Int]] = Set(Left(x), Right(2), Right(4))
scala> split(res13)
res14: (Set[java.lang.String], Set[Int]) = (Set(x),Set(2, 4))
我有点不想要任何业力,因为它是Chris的答案和Viktor的这里的合并..但这里有一个替代方案:
def split[CC[X] <: Traversable[X], A, B](xs: CC[Either[A, B]])
(implicit bfa: CanBuildFrom[Nothing, A, CC[A]], bfb: CanBuildFrom[Nothing, B, CC[B]]) : (CC[A], CC[B]) =
xs.foldLeft((bfa(), bfb())) {
case ((as, bs), l@Left(a)) => (as += a, bs)
case ((as, bs), r@Right(b)) => (as, bs += b)
} match {
case (as, bs) => (as.result(), bs.result())
}
示例:
scala> val eithers: List[Either[String, Int]] = List(Left("Hi"), Right(1))
eithers: List[Either[String,Int]] = List(Left(Hi), Right(1))
scala> split(eithers)
res0: (List[String], List[Int]) = (List(Hi),List(1))
如果您想要更通用且更实用的东西,那么来自 cats 库的
Validated
就是您可能想要的类型。它类似于 Either
可以聚合错误。与 NonEmptyList
结合使用,它会非常强大。
难道不是更优雅的方式吗?
def flatten[E,A](es: List[Either[E,A]]): Either[E,List[A]] = {
@tailrec
def go(tail: List[Either[E,A]], acc: List[A]): Either[E,List[A]] = tail match {
case Nil => Right(acc)
case h::t => h match {
case Left(e) => Left(e)
case Right(a) => go(t, a :: acc)
}
}
go(es, Nil) map { _ reverse }
}
a :: acc
速度很快partitionMap
,可能更快,因为基于构建器的内部实现要分别提取左和右:
val data: List[Either[String, Int]] = List(
Right(1),
Left("Error #1"),
Right(42),
Left("Error #2")
)
val numbers: List[Int] = data.collect { case Right(value) => value }
val errors: List[String] = data.collect { case Left(error) => error }
println(numbers) // List(1, 42)
println(errors) // List(Error #1, Error #2)