使用unit = Try
,Try
不是monad,因为左单位法失败。
Try(expr) flatMap f != f(expr)
但是问题是:Try
是unit = Success
monad,是 Success(expr) flatMap f == f(expr)
吗?
在这种情况下:
{{1}}
所以这是一个单子。
我的理解是否正确?
答案 0 :(得分:4)
基本上,是的。通常monad是用纯函数式语言定义的,其中equality ==具有通常的相等属性,即我们可以用equals替换equals。如果您在Scala的这个子集中,那么您确实可以给出一个表示可能异常计算的参数类型的自然定义。这是一个例子。这个例子实际上是在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
}
答案 1 :(得分:4)
在Alexra的课程论坛中获得答案:
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
的主要功能