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

时间:2016-05-27 08:57:32

标签: scala dependent-type path-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
  }
}

如何编码此方法:

def r[A](x: A)(implicit printer: Printer, show: printer.Show[A]): String =
  printer.show(x)(show)

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

1 个答案:

答案 0 :(得分: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)
}