如何使用包含依赖类型的隐式参数组对此方法进行编码?

Dal*_*and 8 scala path-dependent-type dependent-type

给定Printer具有依赖类型的类型类Show[A]:

trait Printer {
  type Show[A]
  def show[A](x: A)(implicit z: Show[A]): String
}

object Printer {
  // the intent here is this is the dumb fallback
  // and a user can have a better alternative in scope
  implicit val dumbPrinter: Printer = new Printer {
    type Show[A] = DummyImplicit
    def show[A](x: A)(implicit z: DummyImplicit): String = x.toString
  }
}
Run Code Online (Sandbox Code Playgroud)

我如何编码此方法:

def r[A](x: A)(implicit printer: Printer, show: printer.Show[A]): String =
  printer.show(x)(show)
Run Code Online (Sandbox Code Playgroud)

我一直在努力调整@ MilesSabin的主要工作代码https://gist.github.com/milessabin/cadd73b7756fe4097ca0和@ TravisBrown的博客文章https://meta.plasm.us/posts/2015/07/11/ roll-your-own-scala /,但我找不到有效的编码.

Edu*_*bes 0

您可以通过引入中间上下文来强制类型推断一次一步:

object example {

  trait AnyPrinter {
    type Show <: AnyShow
  }

  trait AnyShow {
    type X
    def apply(x: X): String
  }

  def print[P <: AnyPrinter](implicit p: P): print[P] = new print[P]

  class print[P <: AnyPrinter] {
    def it[E](e: E)(implicit s: P#Show { type X = E }): String = s(e)
  }

  // the intent here is this is the dumb fallback
  // and a user can have a better alternative in scope
  implicit object DumbPrinter extends AnyPrinter {
    type Show = AnyDumbShow
  }
  trait AnyDumbShow extends AnyShow {
    def apply(x: X): String = x.toString
  }
  case class DumbShow[Z]() extends AnyDumbShow { type X = Z }
  implicit def dumbShow[Z]:DumbShow[Z] = DumbShow()

  val buh: String = print.it(2)
}
Run Code Online (Sandbox Code Playgroud)