【问题标题】:Is `Try` a monad if unit = Success?如果 unit = Success,“Try”是单子吗?
【发布时间】:2015-04-18 10:48:51
【问题描述】:

对于unit = TryTry 不是单子,因为左单位法则失效。

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

但是问题变成了:Try 是单子,如果 unit = Success

在这种情况下:

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

所以它是一个单子。

我的理解正确吗?

【问题讨论】:

  • 这通常是为Try 编写单元的方式,可以说它仍然违反了组合法则。这些讨论都很随意,不过我个人认为它们没有多大价值。

标签: scala monads


【解决方案1】:

在 coursera 论坛的 Alexey 的帮助下得到了答案:

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

它实际上又输了,当然除非你重新定义 flatMap 以重新抛出异常,从而失去Try 的主要功能

【讨论】:

  • 我认为这个案子完全没用。不使用 Try 来抛出异常。可以编写这样的代码只是 Scala 的一个弱点。如果您仍然不相信,请将此行放入 f:Thread.currentThread().getStackTrace.find( _.getMethodName.contains("flatMap") ) .foreach{_=> throw new RuntimeException("no monad no cry")} 中,您实际上可以杀死任何用 scala 编写的 Monad
【解决方案2】:

基本上,是的。通常 monad 是用纯函数式语言定义的,其中相等 == 具有相等的通常属性,即我们可以用 equals 替换 equals。如果你在这样的 Scala 子集中,那么你确实可以给出一个参数类型的自然定义,它代表可能是异常计算。这是一个例子。该示例实际上恰好在 Scala 的 Leon 验证系统中进行了机械验证 (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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 2015-05-16
    • 2017-05-01
    • 2019-06-20
    • 1970-01-01
    相关资源
    最近更新 更多