为什么AccValidation没有Monad实例? [英] Why can AccValidation not have a Monad instance?
问题描述
从 validation
软件包的文档中:
From the documentation of the validation
package:
AccValidation
数据类型与Either
同构,但是有一个Applicative
实例在错误侧累积.也就是说,如果遇到两个(或多个)错误,则使用Semigroup
操作将其附加.
The
AccValidation
data type is isomorphic toEither
, but has an instance ofApplicative
that accumulates on the error side. That is to say, if two (or more) errors are encountered, they are appended using aSemigroup
operation.
由于此Applicative
实例,因此没有相应的Bind
或Monad
实例. AccValidation
的示例为不是单子的应用函子".
As a consequence of this Applicative
instance, there is no corresponding Bind
or Monad
instance. AccValidation
is an example of, "An applicative functor that is not a monad."
对我来说,这还不是很明显的原因.我可以想像AccValidation
的Monad
实例,其行为类似于Either
-是什么使它不合法?
It isn't evident to me why this is a consequence. I can imagine a Monad
instance for AccValidation
that behaves like Either
- What would make this unlawful?
推荐答案
从机械上讲,AccValidation
的Either
-ish Monad
实例应为
Mechanically, the Either
-ish Monad
instance for AccValidation
would be
-- The (Monoid err) context is not used for anything,
-- it's just there to satisfy the Applicative super-instance
instance (Monoid err) => Monad (AccValidation err) where
return = AccSuccess
AccFailure err >>= f = AccFailure err
AccSuccess x >>= f = f x
这意味着我们有
AccFailure err1 <*> AccFailure err2 = AccFailure (err1 <> err2)
AccFailure err1 `ap` AccFailure err2 = AccFailure err1
违反了<*> = ap
的单子定律.
从直觉上讲,它不能成为monad,因为在monad中,计算的效果(即验证失败)可能取决于先前绑定的结果.但是在失败的情况下,没有结果.因此,在这种情况下,Either
除了短路故障之外别无选择,因为在(>>=)
s右侧没有任何内容可用于后续功能.
Intuitively, it can't be made a monad because in a monad, the effect (i.e. the validation failures) of a computation can depend on previously bound results. But in the case of a failure, there is no result. So Either
has no choice than to short-circuit to failure in that case, since there is nothing to feed to the subsequent functions on right-hand sides of (>>=)
s.
这与应用函子形成鲜明对比,在应用函子中,效果(在这种情况下为验证失败)不能依赖于其他结果,这就是为什么我们无需输入结果即可得到所有验证失败的原因(它们来自何处) ?)从一种计算转移到另一种计算.
This is in stark contrast to applicative functors, where the effect (in this case, the validation failures) cannot depend on other results, which is why we can get all validation failures without having to feed results (where would they come from?) from one computation to the other.
这篇关于为什么AccValidation没有Monad实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!