违反了斯卡拉兹未来单子的左身份法 [英] Violation of the left identity law for Future monads in scalaz
问题描述
假设我为Future
定义了Monad
类型类的实例:
Suppose I define an instance of the Monad
typeclass for Future
:
val futureMonad = new Monad[Future] {
override def point[A](a: ⇒ A): Future[A] =
Future(a)
override def bind[A, B](fa: Future[A])(f: A => Future[B]): Future[B] =
fa flatMap f
}
严格来讲,这不是单子,因为它违反了左派身份定律:
Strictly speaking, this is not a monad, since it violates the law of left identity:
futureMonad.point(a) bind f == f(a)
如果f
引发异常,则左侧的表达式结果将是失败的Future
,而右侧的表达式当然会引发异常.
If f
throws an exception, the result of the expression on the left hand side will be a failed Future
, whereas the right hand side will, of course, throw the exception.
但是这种违反行为的实际含义是什么?系统会因这种不当行为"而以何种方式发生故障?
But what are the practical implications of this violation? In which ways can a system fail as a result of this "misbehavior"?
推荐答案
就理解而言,它仅意味着以下重构不保留语义:
It just means, in terms of for comprehensions, that the following refactoring is not semantics-preserving:
for (fut <- Future(a); x <- f(fut)) yield x ==> f(a)
但这确实是写左身份法则的另一种方式.
But that's just another way of writing the left identity law, really.
要说明无效进一步重构,请执行以下操作:
To explain that invalid refactoring further:
for (fut <- Future(a); x <- f(fut)) yield x
==> for (x <- f(a)) yield x // by left identity law: WRONG, because left identity law does not hold
==> f(a) // by 1st functor law: WRONG, because previous line was wrong
这篇关于违反了斯卡拉兹未来单子的左身份法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!