且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当返回类型为 Option[Error] 时处理快速失败失败

更新时间:2022-04-30 23:14:07

在这种情况下(或至少我已经做到了,我并不为此感到内疚).假设我们有以下内容:

I don't see a principled reason not to use Either[Error, Unit] in a case like this (or at least I've done it, and I don't feel guilty about it). Say we have the following:

def launch(thing: String): Either[String, Unit] = Either.cond(
  thing.nonEmpty,
  println("Launching the " + thing),
  "Need something to launch!"
)

我们可以证明正确的投影单子是适当的懒惰:

We can show that the right projection monad is appropriately lazy:

scala> for {
     |   _ <- launch("flowers").right
     |   _ <- launch("").right
     |   r <- launch("MISSILES").right
     | } yield r
Launching the flowers
res1: Either[String,Unit] = Left(Need something to launch!)

不按需要发射导弹.

值得注意的是,如果您使用 Option 而不是 Either,您所描述的操作只是给定 的第一个"幺半群实例的总和Option(其中加法运算只是orElse).例如,我们可以使用 Scalaz 7 编写以下内容:

It's worth noting that if you use Option instead of Either, the operation you're describing is just the sum given the "First" monoid instance for Option (where the addition operation is just orElse). For example, we can write the following with Scalaz 7:

import scalaz._, Scalaz._

def fst[A](x: Option[A]): Option[A] @@ Tags.First = Tag(x)

def launch(thing: String): Option[String] = if (thing.isEmpty) Some(
  "Need something to launch!"
) else {
  println("Launching the " + thing)
  None
}

现在:

scala> val r: Option[String] = fst(launch("flowers")) |+| fst(
     |   launch("")) |+| fst(launch("MISSILES"))
Launching the flowers
r: Option[String] = Some(Need something to launch!)

再一次,没有导弹.