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

时间:2011-08-29 13:47:03

标签: scala functional-programming scalaz

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

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

修改

我更改了标题,最初要求Either[Seq[A],Seq[B]]反映邮件的正文。

8 个答案:

答案 0 :(得分:27)

编辑:我错过了您的问题标题要求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))

答案 1 :(得分:12)

给出一个起始序列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被定义为一种方法,因此只有在必要时才会根据需要进行评估

答案 2 :(得分: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")
}

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

答案 3 :(得分:9)

这是scalaz代码:

_.sequence

答案 4 :(得分: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)
}

答案 5 :(得分:3)

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

在我们的情况下,我们甚至不需要一个将输入转换为RightLeft来定义分区的函数,因为我们已经有Right和{{1} } s。因此,简单使用Left

这是一个简单的问题,即根据是否有剩余来匹配结果的左和右分区元组:

identity

中间步骤(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

答案 6 :(得分: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]],需要重新打包。

答案 7 :(得分: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))