在Scala中将Eithers与"for"一起使用句法 [英] Using Eithers with Scala "for" syntax
问题描述
据我了解,Scala"for"语法与Haskell的单子"do"语法极为相似.在Scala中,"for"语法通常用于List
和Option
.我想将其与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 List
s and Option
s. I'd like to use it with Either
s, 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.尽管有人说它是右偏的,但您不能在理解中使用它:您必须得到一个LeftProject
或RightProjection
,如下所示:
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屋!