将Seq [Either [String,Int]]转换为(Seq [String],Seq [Int])的有效和/或惯用方式 [英] Efficient and/or idiomatic way to turn Seq[Either[String, Int]] to (Seq[String], Seq[Int])

查看:183
本文介绍了将Seq [Either [String,Int]]转换为(Seq [String],Seq [Int])的有效和/或惯用方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

稍微简化一下,我的问题来自要使用返回Either[String,Int]的函数parse解析的字符串input的列表.

Slightly simplifying, my problem comes from a list of strings input that I want to parse with a function parse returning Either[String,Int].

然后list.map(parse)返回Either的列表.该程序的下一步是格式化一条错误消息,该错误消息汇总在解析的整数列表中传递的所有错误.

Then list.map(parse) returns a list of Eithers. The next step in the program is to format an error message summing up all the errors or passing on the list of parsed integers.

让我们来寻找我正在寻找的解决方案partitionEithers.

Lets call the solution I'm looking for partitionEithers.

通话

partitionEithers(List(Left("foo"), Right(1), Left("bar")))

会给

(List("foo", "bar"),List(1))

最好在标准库中找到类似的内容.如果没有某种清洁,惯用和有效的解决方案,那将是最好的.另外,我可以粘贴到项目中的某种高效实用工具功能也可以.

Finding something like this in the standard library would be best. Failing that some kind of clean, idiomatic and efficient solution would be best. Also some kind of efficient utility function I could just paste into my projects would be ok.

这些 3 早些 >问题.据我所知,这些问题都不符合我的情况,但是那里的一些答案似乎包含了对该问题的有效答案.

I was very confused between these 3 earlier questions. As far as I can tell, neither of those questions matches my case, but some answers there seem to contain valid answers to this question.

推荐答案

我并没有真正理解其他答案的数量.所以这是一个班轮:

I don't really get the amount of contortions of the other answers. So here is a one liner:

scala> val es:List[Either[Int,String]] = 
           List(Left(1),Left(2),Right("A"),Right("B"),Left(3),Right("C"))
es: List[Either[Int,String]] = List(Left(1), Left(2), Right(A), Right(B), Left(3), Right(C))

scala> es.foldRight( (List[Int](), List[String]()) ) { 
         case ( e, (ls, rs) ) => e.fold( l => ( l :: ls, rs), r => ( ls, r :: rs ) ) 
       }
res5: (List[Int], List[String]) = (List(1, 2, 3),List(A, B, C))

这篇关于将Seq [Either [String,Int]]转换为(Seq [String],Seq [Int])的有效和/或惯用方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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