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

标签 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/ ,但我找不到有效的编码。

最佳答案

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

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)
}

关于scala - 如何使用包含依赖类型的隐式参数组对该方法进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37479148/

相关文章:

types - 由类型索引与在 idris 中包含类型

time-complexity - 如何在线性时间内通过 `Fin` 秒枚举列表的元素?

scala - 链接路径相关类型并在 Scala 中具有不同参数列表时实例化它们

scala - 匹配/大小写上的路径相关打字

compiler-construction - Scala:比较新鲜的对象

string - 检查列表中的值是否是字符串的一部分

scala - 如何在 ScalaTest 中显示自定义失败消息?

scala - Akka 路由 : Reply's send to router ends up as dead letters

c++ - 具有单个非类型模板参数类型的函数调用表达式是否依赖于类型?

scala - 路径依赖和内部类