为什么验证不是Monad? [英] Why isn't Validation a Monad?
问题描述
一个示例用例:
def div2(i: Int): Validation[String, Int] =
if (i%2 == 0) Validation.success(i/2)
else Validation.failure("odd")
def div4(i: Int) = for {
a <- div2(i)
b <- div2(a)
} yield b
错误:无法将类型scalaz.Validation[String,Int]
应用于类型为scalaz.Bind
error: Unable to unapply type scalaz.Validation[String,Int]
into a type constructor of kind M[_]
that is classified by the type class scalaz.Bind
我猜测,该错误是由编译器找不到Validation[String, Int]
的Monad
实例引起的.
I guess the error is caused by the compiler can't find a Monad
instance for Validation[String, Int]
我可以为自己做一个,例如:
I can make one for myself, like:
object Instances {
implicit def validationMonad[E] = new Monad[({type L[A] = Validation[E, A]})#L] {
override def point[A](a: => A) =
Validation.success(a)
override def bind[A, B](fa: Validation[E, A])(f: A => Validation[E, B]) =
fa bind f
}
}
但是为什么Validation
还没有呢?毕竟Validation
已经定义了bind
方法.
but why doesn't Validation
have it already? after all, Validation
already has the bind
method defined.
此外,由于另一个复杂 错误import Validation._和import Instances._
放在一起了(这使我无所适从...) > ...
不明确的隐式值:类似validationMonad
(我的实例)和特征ValidationInstances2
中的方法ValidationInstances1
的东西都匹配某些Functor of Validation
...
moreover, I can't have import Validation._
and import Instances._
together anymore (this took me looong to figure out...), because of another complicated error...
ambiguous implicit values: something like both validationMonad
(my instance), and method ValidationInstances1
in trait ValidationInstances2
... both match some Functor of Validation
...
我应该修改scalaz的来源吗?还是我完全想不到的东西〜?
请帮忙〜
should I modify the source of scalaz? or I'm completely missing something~?
please help~
我正在使用scalaz 7.0.0-M2
I'm using scalaz 7.0.0-M2
推荐答案
作为 在Scalaz组中,问题似乎在于ap
会积累错误,而(伪)单原子组合只会对Validation
的值部分起作用.
As discussed in the Scalaz group, the problem seems to be that ap
would accumulate errors whereas (pseudo-)monadic composition would only operate on the value part of Validation
.
因此,一个不能用另一个来表示,因此Validation
不存在monad实例.
Therefore, one cannot be expressed in terms of the other and thus no monad instance exists for Validation
.
这篇关于为什么验证不是Monad?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!