将Eithers列表转换为Either列表的最佳方法? [英] Best way to turn a Lists of Eithers into an Either of Lists?

查看:121
本文介绍了将Eithers列表转换为Either列表的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似下面的代码,其中有一个Eithers列表,并且我想将其转换为Either of Lists(尤其是在这种情况下),如果列表中有任何Lefts,然后我返回其中一个列表的左侧,否则返回一个列表中的右侧.

I have some code like the below, where I have a list of Eithers, and I want to turn it into an Either of Lists ... in particular (in this case), if there are any Lefts in the list, then I return a Left of the list of them, otherwise I return a Right of the list of the rights.

val maybe: List[Either[String, Int]] = getMaybe
val (strings, ints) = maybe.partition(_.isLeft)
strings.map(_.left.get) match {
  case Nil => Right(ints.map(_.right.get))
  case stringList => Left(stringList)
}

打电话给get总是让我觉得我一定很想念东西.

Calling get always makes me feel like I must be missing something.

是否有更惯用的方式做到这一点?

Is there a more idiomatic way to do this?

推荐答案

data.partition(_.isLeft) match {                            
  case (Nil,  ints) => Right(for(Right(i) <- ints) yield i)        
  case (strings, _) => Left(for(Left(s) <- strings) yield s)
}

通过一遍:

data.partition(_.isLeft) match {                            
  case (Nil,  ints) => Right(for(Right(i) <- ints.view) yield i)        
  case (strings, _) => Left(for(Left(s) <- strings.view) yield s)
}

这篇关于将Eithers列表转换为Either列表的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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