如何将Seq [[A,B]]减少到[A,Seq [B]] [英] How to reduce a Seq[Either[A,B]] to a Either[A,Seq[B]]

查看:238
本文介绍了如何将Seq [[A,B]]减少到[A,Seq [B]]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个 Seq [或者[String,A]] 和 Left 作为错误消息的序列。我想获得任何[String,Seq [A]] ,我得到 Right (这将是一个 Seq [A] ),如果序列的所有元素都是 Right 。如果至少有一个 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.

我改变了标题,最初要求 [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.

推荐答案

编辑:我错过了要求标题 [Seq [A],Seq [B]] ,但我确实读过我想获得第一条错误消息或所有错误消息的串联,这会给你前者: / 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 [[A,B]]减少到[A,Seq [B]]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆