简体   繁体   English

如果单位=成功,是否尝试monad?

[英]Is it Try a monad if unit = Success?

With unit = Try , Try is not a monad, because the left unit law fails. 使用unit = TryTry不是monad,因为左单位法失败了。

 Try(expr) flatMap f  !=  f(expr)

But what is the question becomes: Is it Try a monad, if unit = Success ? 但是问题是什么:如果unit = Success ,它是否Try单子?

In this case: 在这种情况下:

 Success(expr) flatMap f  ==  f(expr)

So it is a monad. 所以这是一个单子。

Is my understanding correct? 我的理解是否正确?

Essentially, yes. 基本上,是的。 Usually monads are defined in a purely functional language, where equality == has the usual properties of equality, ie we can substitute equals for equals. 通常monad是用纯函数式语言定义的,其中equality ==具有通常的相等属性,即我们可以用equals替换equals。 If you are within such subset of Scala, then you can indeed give a natural definition of a parametric type that represents possibly exceptional computation. 如果您在Scala的这个子集中,那么您确实可以给出一个表示可能异常计算的参数类型的自然定义。 Here is an example. 这是一个例子。 The example actually happens to mechanically verify in the Leon verification system for Scala ( http://leon.epfl.ch ). 这个例子实际上是在Leon的验证系统中对Scala进行机械验证( http://leon.epfl.ch )。

import leon.lang._
object TryMonad {

  // Exception monad similar to Option monad, with an error message id for None  
  sealed abstract class M[T] {
    def bind[S](f: T => M[S]): M[S] = {
      this match {
        case Exc(str) => Exc[S](str)
        case Success(t) => f(t)
      }
    }
  }
  case class Exc[T](err: BigInt) extends M[T]
  case class Success[T](t: T) extends M[T]

  // unit is success
  def unit[T](t:T) = Success(t)

  // all laws hold 
  def leftIdentity[T,S](t: T, f: T => M[S]): Boolean = {
    unit(t).bind(f) == f(t)
  }.holds

  def rightIdentity[T](m: M[T]): Boolean = {
    m.bind(unit(_)) == m
  }.holds

  def associativity[T,S,R](m: M[T], f: T => M[S], g: S => M[R]): Boolean = {
    m.bind(f).bind(g) == m.bind((t:T) => f(t).bind(g))
  }.holds
}

Get an answer from the help of Alexey in the coursera forum: 在课程论坛中从Alexey的帮助中获得答案:

When unit = Success , for the left unit law: unit = Success ,对于左单位法则:

Success(throw new Exception) flatMap f == f(throw new Exception) // holds
Success(s) flatMap (x => throw new Exception) == Failure(new Exception) // does not hold

It actually loses again, unless of course you redefine flatMap to re-throw the exceptions, thus losing the main functionality of the Try 它实际上会再次丢失,除非您重新定义flatMap以重新抛出异常,从而失去了Try的主要功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM