我们可以根据 Maybe monad 或 Continuation monad 来理解错误 monad 吗?

Can we understanding the error monad in terms of the Maybe monad or the Continuation monad?

我正在查看 Scala 中的 the following code for handling errors

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 中看到 code here for handling exceptions using the 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 explains exception handling in terms of continuations:

(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]))

(现在我知道 that all monads are continuations in a sense - 我暂时把它搁置一旁。如果我犯了一个严重的错误 - 请帮助我,以便我可以更正问题)。

我正在努力思考上面的 Scala 代码。我正在尝试确定它是基于 Maybe 还是 Continuations。

我的问题是:我们可以根据 Maybe monad 或 Continuation monad 来理解错误 monad 吗?

"In terms of" 是一个松散的短语。您展示的 Result monad 比 Maybe monad 更通用;事实上,我会说 MaybeResult 的特例。反过来,延续更普遍, Result 可以看作是延续的特例 - 但这与所有单子都是延续的意义相同,所以如果这不是你要问的,我不确定你会问什么。 (我不认为延续的观点有助于理解,因为延续是一个非常普遍的结构,但也许你这样做?但如果是这样,它必须是所有单子都是延续的意义)

我建议尝试直接理解 Result;这很简单,与您给出的其他两个示例的区别很重要。也就是说,它 可能 有助于将其视为“Maybe,但 None 具有不同的可能值(Fail(e) 任何 e: Error) 而不是只有一个”;是你想要的 "in terms of" 吗?