为什么验证不是Monad? [英] Why isn't Validation a Monad?

查看:97
本文介绍了为什么验证不是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆