如何将Seq [Either [A,B]]减少为Either [A,Seq [B]]? [英] How to reduce Seq[Either[A,B]] to Either[A,Seq[B]]?
问题描述
给出一个序列Seq[Either[String,A]]
,其中Left
是错误消息.我想获得一个Either[String,Seq[A]]
,如果序列中的所有元素都是Right
,那么我会得到一个Right
(将是一个Seq[A]
).如果至少有一个Left
(错误消息),我想获取第一条错误消息或所有错误消息的串联.
Given a sequence of eithers Seq[Either[String,A]]
with Left
being an error message. I want to obtain an Either[String,Seq[A]]
where I get a Right
(which will be a Seq[A]
), if all elements of the sequence are Right
. If there is at least one Left
(an error message), I'd like to obtain the first error message or a concatenation of all error messages.
您当然可以发布scalaz代码,但我也对不使用它的代码感兴趣.
Of course you can post scalaz code but I'm also interested in code not using it.
我更改了标题,该标题最初要求输入Either[Seq[A],Seq[B]]
来反映邮件的正文.
I've changed the title, which originally asked for an Either[Seq[A],Seq[B]]
to reflect the body of the message.
推荐答案
我想念您的问题标题要求输入Either[Seq[A],Seq[B]]
,但我确实读过我想获得第一条错误消息或串联所有错误消息",那么前者将为您提供:
I missed that the title of your question asked for Either[Seq[A],Seq[B]]
, but I did read "I'd like to obtain the first error message or a concatenation of all error messages", and this would give you the former:
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:
Using 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))
这篇关于如何将Seq [Either [A,B]]减少为Either [A,Seq [B]]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!