【问题标题】:Scala implicit natural transform with monad failing to find functions for for comprehensionScala 隐式自然变换,monad 无法找到用于理解的函数
【发布时间】:2015-06-15 03:35:43
【问题描述】:

我的代码是这样的:

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 识别隐含,在编译时它无法解析 map 函数。有什么我明显做错了吗?

【问题讨论】:

  • 一目了然,您有什么理由不想明确地应用pipe?此外,如果协方差给您带来麻烦,我也不会感到惊讶。
  • 绝对是一个选择。目前我一直在隐式管道和显式绑定。不过,很高兴了解它是否可行,或者为什么不可行。两个隐式之间的协方差可能会导致问题?
  • 使高级类型保持不变。没有区别。

标签: scala monads scalaz implicits


【解决方案1】:

我能够通过创建自定义组合隐式类来解决此问题。只要 import 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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-05
    • 2019-04-02
    • 2018-09-23
    • 2016-08-18
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 2018-05-06
    相关资源
    最近更新 更多