【问题标题】:Can we understanding the error monad in terms of the Maybe monad or the Continuation monad?我们可以根据 Maybe monad 或 Continuation monad 来理解 error monad 吗?
【发布时间】:2015-03-01 11:34:00
【问题描述】:

我正在查看 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 来理解 error monad 吗?

【问题讨论】:

    标签: scala clojure monads continuations maybe


    【解决方案1】:

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

    我建议尝试直接了解Result;它非常简单,与您提供的其他两个示例的区别很重要。也就是说,它可能有助于将其视为“Maybe,但None 的可能值不同(Fail(e) 用于任何e: Error)而不是只有一个”;那是你想要的“根据”吗?

    【讨论】:

    • 感谢您的热心回答和慷慨的态度。
    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    相关资源
    最近更新 更多