Scala要么没有`flatMap`& Either.left/.right的含义 [英] Scala's Either not Having `flatMap` & Meaning of Either.left/.right

查看:80
本文介绍了Scala要么没有`flatMap`& Either.left/.right的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看Haskell的Either Monad,有一个>>=函数.

Looking at Haskell's Either Monad, there's a >>= function.

Prelude Map> let add100 = \x -> Right (x+100 :: Int)

Prelude Map> x
Right 5
Prelude Map> x >>= add100
Right 105

Prelude Map> let y = Left "..." :: Either String Int
Prelude Map> y >>= add100
Left "..."

但是,为什么Scala的Either[A,B]没有flatMap,即等同于>>=函数?

However, why doesn't Scala's Either[A,B] have a flatMap, i.e. equivalent to >>= function?

scala> e
res5: Either[String,Int] = Right(1)

scala> e.
asInstanceOf   fold           isInstanceOf   isLeft         isRight
joinLeft       joinRight      left           right          swap
toString

还有,leftright是什么意思?

scala> e.left
res6: scala.util.Either.LeftProjection[String,Int] = LeftProjection(Right(1))

scala> e.right
res7: scala.util.Either.RightProjection[String,Int] = RightProjection(Right(1))

推荐答案

您可以使用需要两个功能的fold,一个用于左,另一个用于右,或者使用right投影视图:

You can either use fold which requires two functions, one for left and one for right, or use the right projection view:

val e: Either[String, Int] = Right(5)

def add100(i: Int): Either[String, Int] = Right(i + 100)

e.fold(identity, add100)  // Right(105)
e.right.flatMap(add100)   // Right(105)

因此,投影视图使您可以看到Either实例,该实例将通过左或右类型进行映射. Either scala-doc帮助文件.

So the projection views allow you to see an Either instance as something that will be mapped through the left or right type. This is explained in the Either scala-doc help file.

如果您熟悉Haskell,则 ScalaZ 库可能适合您,它有自己的两者都称为\/(如此处所述).

If you are familiar with Haskell, the ScalaZ library might be for you, it has its own 'either' abstraction called \/ (as described here).

这篇关于Scala要么没有`flatMap`& Either.left/.right的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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