How to turn a List of Eithers to a Either of Lists using scalaz.MonadPlus.separate

蹲街弑〆低调 提交于 2020-01-25 19:22:07

问题


How to turn a List of Eithers to a Either of Lists, using MonadPlus.separate?

In this answer the author claims this solution, but fails to provide the imports or complete example:

If scalaz is one of your dependencies I would simply use separate:

val el : List[Either[Int, String]] = List(Left(1), Right("Success"), Left(42))

scala> val (lefts, rights) = el.separate
lefts: List[Int] = List(1, 42)
rights: List[String] = List(Success)

Is this a real working solution? I see that MonadPlus has a separate function but I still didn't manage to make it work.

ps: I am aware I can achieve this without scalaz, such as the example below. However, in this question I am asking how to use scalaz.MonadPlus.separate to achieve this.

(lefts, rights) = (el.collect { case Left(left) => left }, el.collect { case Right(right) => right })

回答1:


That solution is correct, you're just missing import scalaz.Scalaz._ here.



来源:https://stackoverflow.com/questions/36878459/how-to-turn-a-list-of-eithers-to-a-either-of-lists-using-scalaz-monadplus-separa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!