正确的做法是不使用 Scala 进行理解

Fla*_*nix 0 monads scala either

背景

我正在尝试将 Scala 的推导式与Either类型结合使用,即使用Right. 然而,尽管我付出了努力,我还是收到错误并且没有任何效果。

代码

我正在使用 scala 的 repl 进行一些测试。这是我能想到的最简单的用例:

scala> for {
     |   x <- Right(1)
     |   y <- Right(2)
     |   z <- Right(3)
     | } yield x + y + z
Run Code Online (Sandbox Code Playgroud)

您会看到它基本上是此页面的副本:

https://www.scala-lang.org/api/2.12.7/scala/util/Either.html

问题

但是,此操作失败并出现以下错误:

<console>:13: error: value flatMap is not a member of scala.util.Right[Nothing,Int]
         x <- Right(1)
                   ^
<console>:14: error: value flatMap is not a member of scala.util.Right[Nothing,Int]
         y <- Right(2)
                   ^
<console>:15: error: value map is not a member of scala.util.Right[Nothing,Int]
         z <- Right(3)
                   ^
Run Code Online (Sandbox Code Playgroud)

我正在使用以下版本的 scala:

Welcome to Scala 2.11.12 (OpenJDK 64-Bit Server VM, Java 11.0.13).
Type in expressions for evaluation. Or try :help.
Run Code Online (Sandbox Code Playgroud)

我知道对 Either 进行了一些更改,因此它变得偏右,但我不知道这些更改会如何影响此示例。

我缺少什么?

Vla*_*ski 6

在 scala 2.11 中, Either 不是Monad。其中缺少诸如 flatMap 和 map 之类的组合器。相反,您可以调用.right.left来获取具有组合器的RightProjectionLeftProjection 。您需要正确地预测您的“任一” 。下面的代码将返回Right(6)

  for {
    x <- Right(1).right
    y <- Right(2).right
    z <- Right(3).right
  } yield x + y + z
Run Code Online (Sandbox Code Playgroud)