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

时间:2015-01-03 10:43:20

标签: scala clojure monads continuations maybe

我在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吗?

1 个答案:

答案 0 :(得分:2)

“在”方面是一个松散的短语。你展示的Result monad比Maybe monad更通用;的确,我会说MaybeResult的一个特例。反过来,延续仍然更为笼统,Result可以看作是延续的一个特例 - 但这与所有单子都是延续的意义相同,所以如果这不是你所要求的,我不确定你能问什么。 (我没有发现延续视角有助于理解,因为延续是一个非常一般的结构,但也许你这样做?但如果是这样,那就必须是所有monad都是连续的意义)

我建议直接了解Result;它很简单,与你提供的其他两个例子的区别很重要。也就是说,它可能帮助将其视为“Maybe,但NoneFail(e)对于任何e: Error)具有不同的可能值只有一个“;那就是“你想要的”吗?