如何在Scala中编写Haskell-do-notation

ryo*_*ryo 4 haskell scala

我使用do-nation编写了以下Haskell代码.

我想将其转换为Scala代码

main :: IO ()
main = do
  print $ func1 (Right  1) (Right 2)
  print $ func1 (Right 10) (Right 3)


func1 :: Either String Int -> Either String Int -> Either String Double
func1 e1 e2 = do
  v1 <- e1
  v2 <- e2
  if v1 < v2
    then Right 1.515151  -- No meaning
    else Left  "some error"
Run Code Online (Sandbox Code Playgroud)

这是Haskell的输出

Right 1.515151
Left "some error"
Run Code Online (Sandbox Code Playgroud)

我写了Scala代码,如下所示.但是当我看到时result <- if(v1 < v2)...,我感到很奇怪yield result.

object Main {
  def main(args: Array[String]): Unit = {
    println(func1(Right(1))(Right(2)))
    println(func1(Right(10))(Right(3)))
  }

  def func1(e1: Either[String, Int])(e2: Either[String, Int]): Either[String, Double] =
    for{
      v1 <- e1
      v2 <- e2

      // Weird...
      result <- if(v1 < v2)
                  Right(1.515151)
                else
                  Left("some error")
    } yield result
}
Run Code Online (Sandbox Code Playgroud)

这是Scala的输出

Right(1.515151)
Left(some error)
Run Code Online (Sandbox Code Playgroud)

我想写下吼叫.但斯卡拉不允许我写.

  // Invalid Scala Code
  def func1(e1: Either[String, Int])(e2: Either[String, Int]): Either[String, Double] =
    for{
      v1 <- e1
      v2 <- e2
    } {
      if(v1 < v2)
          Right(1.515151)
        else
          Left("some error")
    }
Run Code Online (Sandbox Code Playgroud)

你能告诉我你以漂亮的方式写作的想法吗?

jwv*_*wvh 5

它可以被美化一些.

for {
  v1  <- e1
  v2  <- e2
  res <- Either.cond(v1 < v2, 1.515151, "some error")
} yield res
Run Code Online (Sandbox Code Playgroud)

如果放弃一个保护条件会很好,但根据Scala文档,这是不支持的,因为Either没有withFilter方法.