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

前端之家收集整理的这篇文章主要介绍了如何在Scala中编写Haskell-do-notation前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用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"

这是Haskell的输出

Right 1.515151
Left "some error"

我写了Scala代码,如下所示.但是当我查看结果< - if if(v1< v2)...并且得到结果时,我感到很奇怪.

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
}

这是Scala的输出

Right(1.515151)
Left(some error)

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

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

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

解决方法

它可以被美化一些.

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

只是投入一个保护条件会很好,但根据Scala docs,这是不支持的,因为要么没有withFilter方法.

猜你在找的Scala相关文章