在Scala中将Eithers与"for"一起使用句法 [英] Using Eithers with Scala "for" syntax

查看:156
本文介绍了在Scala中将Eithers与"for"一起使用句法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,Scala"for"语法与Haskell的单子"do"语法极为相似.在Scala中,"for"语法通常用于ListOption.我想将其与Either一起使用,但是默认导入中没有必要的方法.

As I understand it, Scala "for" syntax is extremely similar to Haskell's monadic "do" syntax. In Scala, "for" syntax is often used for Lists and Options. I'd like to use it with Eithers, but the necessary methods are not present in the default imports.

for {
  foo <- Right(1)
  bar <- Left("nope")
} yield (foo + bar)

// expected result: Left("nope")
// instead I get "error: value flatMap is not a member..."

可以通过某些导入使用此功能吗?

Is this functionality available through some import?

有一个小障碍:

for {
  foo <- Right(1)
  if foo > 3
} yield foo
// expected result: Left(???)

对于列表,它将为List().对于Option,它将为None. Scala标准库是否为此提供了解决方案? (或者scalaz?)如何?假设我想为Either提供自己的"monad实例",我该怎么做?

For a List, it would be List(). For Option, it would be None. Do the Scala standard libraries provide a solution to this? (Or perhaps scalaz?) How? Suppose I wanted to provide my own "monad instance" for Either, how could I do that?

推荐答案

在Scala 2.11和更早版本中,不起作用,因为Either不是monad.尽管有人说它是右偏的,但您不能在理解中使用它:您必须得到一个LeftProjectRightProjection,如下所示:

It doesn't work in scala 2.11 and earlier because Either is not a monad. Though there's talk of right-biasing it, you can't use it in a for-comprehension: you have to get a LeftProject or RightProjection, like below:

for {
  foo <- Right[String,Int](1).right
  bar <- Left[String,Int]("nope").right
} yield (foo + bar)

顺便说一句,返回Left("nope").

在Scalaz上,您将Either替换为Validation.有趣的事实:Either的原始作者是Scalaz的作者之一Tony Morris.他想使Either右偏,但同事对此深信不疑.

On Scalaz, you'd replace Either with Validation. Fun fact: Either's original author is Tony Morris, one of Scalaz authors. He wanted to make Either right-biased, but was convinced otherwise by a colleague.

这篇关于在Scala中将Eithers与"for"一起使用句法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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