如何使用 scalaz.MonadPlus.separate 将一个列表转换为一个列表 [英] How to turn a List of Eithers to a Either of Lists using scalaz.MonadPlus.separate

查看:54
本文介绍了如何使用 scalaz.MonadPlus.separate 将一个列表转换为一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 MonadPlus 将 EithersList 转换为 ListsEither.分开?

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

this answer 中,作者声称此解决方案,但未能提供导入或完整示例:

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

如果 scalaz 是您的依赖项之一,我会简单地使用单独的:

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)

这是一个真正有效的解决方案吗?我看到 MonadPlus 有一个 separate 功能,但我仍然没有设法让它起作用.

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:我知道我可以在没有 scalaz 的情况下实现这一点,例如下面的示例.但是,在这个问题中,我问的是如何使用 scalaz.MonadPlus.separate 来实现这一点.

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 })

推荐答案

那个解决方案是正确的,你只是缺少 import scalaz.Scalaz._ 在这里.

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

这篇关于如何使用 scalaz.MonadPlus.separate 将一个列表转换为一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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