Scala要么没有`flatMap`& Either.left/.right的含义 [英] Scala's Either not Having `flatMap` & Meaning of 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
还有,left
和right
是什么意思?
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屋!