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

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

问题描述

给定一个 Seq[Either[String,A]] 的序列,其中 Left 是一条错误消息.我想获得一个 Either[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.

当然,您可以发布 cat 或 scalaz 代码,但我也对不使用它的代码感兴趣.

Of course you can post cats or 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]] 减少为 [A,Seq[B]]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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