Scala隐式自然变换与monad无法找到理解的函数

时间:2015-04-09 16:33:32

标签: scala monads scalaz implicits

我的代码是:

class SourceService[Out[+_]](implicit monad:Monad[Out]) {
  def doSomething:Out[String] =
    monad.point("Result")
}

class SimplifiedPipe[Out[+_], In[+_]]
  (myService:SourceService[In])
  (implicit monad:Monad[Out], pipe: ~>[In, Out]) {

  implicit def ~>[I[+ _], O[+ _], T](value: I[T])(implicit nt: ~>[I, O]): O[T]
  = nt.apply(value)

  implicit class lift[T, O[+ _]](m: O[T])(implicit monad: Monad[O]) {
    def flatMap[S](f: T => O[S]): O[S] =
      monad.bind(m)(f)

    def map[S](f: T => S): O[S] =
      monad.map(m)(f)

    def foreach(f: T => Unit) =
      monad.map(m)(f)
  }

  def run: Out[String] =
    for {
      s <- myService.doSomething
    } yield s
}

并且intellij识别出implicits,在编译时它无法解析map函数。我在这里显然做错了什么?

1 个答案:

答案 0 :(得分:0)

我能够通过创建自定义组合隐式类来解决这个问题。只要导入scalaz._不在范围内,这也可以工作。

implicit class PipeMonad[Out[+_], In[+_], A](in: In[A])(implicit monad: Monad[Out], pipe:In ~> Out) {
  def flatMap[T](f:A => Out[T]):Out[T] =
    monad.bind(pipe(in))(f)
  def map[T](f:A => T):Out[T] =
    monad.map(pipe(in))(f)
}