如何将Seq [A,B]]减少到[A,Seq [B]]?

问题描述 投票:42回答:8

鉴于一系列eithers Seq[Either[String,A]]Left是一个错误信息。我想获得一个Either[String,Seq[A]],我得到一个Right(将是一个Seq[A]),如果序列的所有元素都是Right。如果至少有一个Left(错误消息),我想获取第一条错误消息或所有错误消息的串联。

当然你可以发布scalaz代码,但我也对不使用它的代码感兴趣。

编辑

我改变了标题,最初要求Either[Seq[A],Seq[B]]反映信息的正文。

scala functional-programming scalaz
8个回答
28
投票

编辑:我错过了你的问题的标题要求Either[Seq[A],Seq[B]],但我确实读过“我想获取第一条错误消息或所有错误消息的串联”,这将给你前者:

def sequence[A, B](s: Seq[Either[A, B]]): Either[A, Seq[B]] =
  s.foldRight(Right(Nil): Either[A, List[B]]) {
    (e, acc) => for (xs <- acc.right; x <- e.right) yield x :: xs
  }

scala> sequence(List(Right(1), Right(2), Right(3)))
res2: Either[Nothing,Seq[Int]] = Right(List(1, 2, 3))

scala> sequence(List(Right(1), Left("error"), Right(3)))
res3: Either[java.lang.String,Seq[Int]] = Left(error)

使用Scalaz:

val xs: List[Either[String, Int]] = List(Right(1), Right(2), Right(3))

scala> xs.sequenceU
res0:  scala.util.Either[String,List[Int]] = Right(List(1, 2, 3))

13
投票

给出一个起始序列xs,这是我的看法:

xs collectFirst { case x@Left(_) => x } getOrElse
  Right(xs collect {case Right(x) => x})

这是回答问题的主体,只获得第一个错误作为Either[String,Seq[A]]。这显然不是标题中问题的有效答案


要返回所有错误:

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

请注意,rights被定义为一种方法,因此只有在必要时才会根据需要进行评估


9
投票

它应该工作:

def unfoldRes[A](x: Seq[Either[String, A]]) = x partition {_.isLeft} match {
  case (Seq(), r) => Right(r map {_.right.get})
  case (l, _) => Left(l map {_.left.get} mkString "\n")
}

你左右分开你的结果,如果左边是空的,建立一个右边,否则,建立一个左边。


9
投票

这是scalaz代码:

_.sequence


3
投票

基于Kevin的解决方案,并从Haskell的Either类型中窃取一点,您可以创建一个方法partitionEithers,如下所示:

def partitionEithers[A, B](es: Seq[Either[A, B]]): (Seq[A], Seq[B]) =
  es.foldRight (Seq.empty[A], Seq.empty[B]) { case (e, (as, bs)) =>
    e.fold (a => (a +: as, bs), b => (as, b +: bs))
  }

并使用它来构建您的解决方案

def unroll[A, B](es: Seq[Either[A, B]]): Either[Seq[A], Seq[B]] = {
  val (as, bs) = partitionEithers(es)
  if (!as.isEmpty) Left(as) else Right(bs)
}

3
投票

Scala 2.13开始,大多数集合都提供了partitionMap方法,该方法基于将项目映射到RightLeft的函数来划分元素。

在我们的例子中,我们甚至不需要将我们的输入转换为RightLeft来定义分区的函数,因为我们已经有Rights和Lefts。因此简单使用identity

然后,根据是否存在lefts,匹配得到的左派和权限的分区元组是一件简单的事情:

eithers.partitionMap(identity) match {
  case (Nil, rights)       => Right(rights)
  case (firstLeft :: _, _) => Left(firstLeft)
}

// * val eithers: List[Either[String, Int]] = List(Right(1), Right(2), Right(3))
//         => Either[String,List[Int]] = Right(List(1, 2, 3))
// * val eithers: List[Either[String, Int]] = List(Right(1), Left("error1"), Right(3), Left("error2"))
//         => Either[String,List[Int]] = Left("error1")

中间步骤的详细信息(partitionMap):

List(Right(1), Left("error1"), Right(3), Left("error2")).partitionMap(identity)
// => (List[String], List[Int]) = (List("error1", "error2"), List(1, 3))

0
投票

我不习惯使用Either - 这是我的方法;也许有更优雅的解决方案:

def condense [A] (sesa: Seq [Either [String, A]]): Either [String, Seq [A]] = {
  val l = sesa.find (e => e.isLeft)
  if (l == None) Right (sesa.map (e => e.right.get)) 
  else Left (l.get.left.get)
}

condense (List (Right (3), Right (4), Left ("missing"), Right (2)))
// Either[String,Seq[Int]] = Left(missing)
condense (List (Right (3), Right (4), Right (1), Right (2)))
// Either[String,Seq[Int]] = Right(List(3, 4, 1, 2))

Left (l.get.left.get)看起来有点滑稽,但l本身是一个[A,B],而不是一个[A,Seq [B]],需要重新包装。


0
投票

我的回答类似于@Garrett Rowe:但是它使用foldLeft(参见:Why foldRight and reduceRight are NOT tail recursive?)并且在Seq之前,而不是附加到Seq(参见:Why is appending to a list bad?)。

scala> :paste
// Entering paste mode (ctrl-D to finish)

def partitionEitherSeq[A,B](eitherSeq: Seq[Either[A,B]]): (Seq[A], Seq[B]) =
  eitherSeq.foldLeft(Seq.empty[A], Seq.empty[B]) { (acc, next) =>
  val (lefts, rights) = acc
  next.fold(error => (lefts :+ error, rights), result => (lefts, rights :+ result))
}

// Exiting paste mode, now interpreting.

partitionEitherSeq: [A, B](eitherSeq: Seq[Either[A,B]])(Seq[A], Seq[B])

scala> partitionEitherSeq(Seq(Right("Result1"), Left("Error1"), Right("Result2"), Right("Result3"), Left("Error2")))
res0: (Seq[java.lang.String], Seq[java.lang.String]) = (List(Error1, Error2),List(Result1, Result2, Result3))
© www.soinside.com 2019 - 2024. All rights reserved.