【发布时间】:2020-04-16 14:37:08
【问题描述】:
查看 Haskell 的 Either Monad,有一个 >>= 函数。
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,即等效于 >>= 函数?
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))
【问题讨论】: