我正在阅读LYAHFGG并且为了锻炼,我为monad写了以下特征:
trait Monad[M[_]] extends Functor[M] with Applicative[M] { self =>
def id[x](u: x): M[x]
def flatMap[x, y](mx: M[x])(f: x => M[y]): M[y]
def map[x, y](mx: M[x])(f: x => y): M[y] = flatMap(mx)(u => id(f(u)))
def flatten[y](mmy: M[M[y]]): M[y] = flatMap(mmy)(u => u)
/** Casts this monad as a monoid. */
def asMonoid[x]: Monoid[x => M[x]] = new Monoid[x => M[x]] {
def id = self.id[x]
def op(f: x => M[x], g: x => M[x]) = u => flatMap(flatMap(self.id(u))(f))(g)
}
使用lambdas类型的函数的monad实例:
implicit def functionMonad[z]: Monad[({type λ[α] = z => α})#λ] = new Monad[({type λ[α] = z => α})#λ] {
def flatMap[x, y](mx: z => x)(f: x => z => y): z => y = w => f(mx(w))(w)
def id[x](u: x): z => x = _ => u
override def map[x, y](mx: z => x)(f: x => y) = f compose mx
}
但是如果我定义一个像
这样的隐式类implicit class withOps[M[_], X](mx: M[X])(implicit M: Monad[M]) {
def map[Y](f: X => Y): M[Y] = M.map(mx)(f)
}
如果mx
是函数,则编译器无法找到上面隐式定义的functionMonad
。这有什么问题?