我正在查看以下用于处理Scala 中的错误的代码:
package challenge1
import core._, Syntax._
sealed trait Error
case class Explosion(exception: Throwable) extends Error
case object NotFound extends Error
case object InvalidRequest extends Error
case object InvalidMethod extends Error
case object Unauthorized extends Error
object Error {
implicit def ErrorEqual =
Equal.derived[Error]
}
case class Fail[A](error: Error) extends Result[A]
case class Ok[A](value: A) extends Result[A]
sealed trait Result[A] {
def fold[X](
fail: Error => X,
ok: A => X
): X = this match {
case Fail(error) => fail(error)
case Ok(value) => ok(value)
}
def map[B](f: A => B): Result[B] =
flatMap(f andThen Result.ok)
def flatMap[B](f: A => Result[B]): Result[B] =
fold(Result.fail, f)
def getOrElse(otherwise: => A): A =
fold(_ => otherwise, identity)
def |||(alternative: => Result[A]): Result[A] =
fold(_ => alternative, _ => this)
}
...
现在我可以在这里看到使用Clojure中的 Maybe Monad 处理异常的代码:
(use '[clojure.contrib.monads :only [maybe-m]])
(defmacro maybe
([bindings return]
`(domonad maybe-m ~bindings ~return))
([bindings return else]
`(let [result# (maybe ~bindings ~return)]
(if (nil? result#)
~else
result#))))
在这里,Jim Duey 解释了关于 continuation 的异常处理:
(defn mf-a [x]
(println "starting mf-a")
(fn [c]
(println "completing mf-a")
(c (inc x))))
(defn mf-b [x]
(println "starting mf-b")
(fn [c]
(println "completing mf-b")
(c (* 2 x))))
(defn mf-c [x]
(println "starting mf-c")
(fn [c]
(println "completing mf-c")
(c (dec x))))
(def fn8 (m-chain [mf-a mf-b mf-c]))
(现在我知道所有单子在某种意义上都是延续- 我现在将把它放在一边。如果我犯了一个严重的错误 - 请帮助我,以便我可以纠正这个问题)。
我正试图围绕上面的这个 Scala 代码。我正在尝试确定它是基于Maybe还是基于Continuations。
我的问题是:我们可以根据 Maybe monad 或 Continuation monad 来理解 error monad 吗?