【发布时间】:2015-04-30 02:05:18
【问题描述】:
给定一个简单的参数化类型,比如class LK[A],我可以写
// or simpler def tagLK[A: TypeTag] = typeTag[LK[A]]
def tagLK[A](implicit tA: TypeTag[A]) = typeTag[LK[A]]
tagLK[Int] == typeTag[LK[Int]] // true
现在我想为class HK[F[_], A] 写一个模拟:
def tagHK[F[_], A](implicit ???) = typeTag[HK[F, A]]
// or some other implementation?
tagHK[Option, Int] == typeTag[HK[Option, Int]]
这可能吗?我试过了
def tagHK[F[_], A](implicit tF: TypeTag[F[_]], tA: TypeTag[A]) = typeTag[HK[F, A]]
def tagHK[F[_], A](implicit tF: TypeTag[F], tA: TypeTag[A]) = typeTag[HK[F, A]]
但由于显而易见的原因,两者都不起作用(在第一种情况下,F[_] 是存在类型而不是更高的类型,在第二种情况下,TypeTag[F] 无法编译)。
我怀疑答案是“不可能”,但如果不是,我会很高兴。
编辑:我们目前使用WeakTypeTags 如下(略微简化):
trait Element[A] {
val tag: WeakTypeTag[A]
// other irrelevant methods
}
// e.g.
def seqElement[A: Element]: Element[Seq[A]] = new Element[Seq[A]] {
val tag = {
implicit val tA = implicitly[Element[A]].tag
weakTypeTag[Seq[A]]
}
}
trait Container[F[_]] {
def lift[A: Element]: Element[F[A]]
// note that the bound is always satisfied, but we pass the
// tag explicitly when this is used
def tag[A: WeakTypeTag]: WeakTypeTag[F[A]]
}
val seqContainer: Container[Seq] = new Container[Seq] {
def lift[A: Element] = seqElement[A]
}
如果我们将WeakTypeTag 替换为TypeTag,所有这些都可以正常工作。不幸的是,这不会:
class Free[F[_]: Container, A: Element]
def freeElement[F[_]: Container, A: Element] {
val tag = {
implicit val tA = implicitly[Element[A]].tag
// we need to get something like TypeTag[F] here
// which could be obtained from the implicit Container[F]
typeTag[Free[F, A]]
}
}
【问题讨论】:
-
@BenReich 是的,确实如此。谢谢!
标签: scala higher-kinded-types scala-reflect