构造高等级类型的TypeTag

Ale*_*nov 10 scala higher-kinded-types scala-reflect

给出一个简单的参数化类型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
Run Code Online (Sandbox Code Playgroud)

现在我想写一个类似的class HK[F[_], A]:

def tagHK[F[_], A](implicit ???) = typeTag[HK[F, A]] 
// or some other implementation?

tagHK[Option, Int] == typeTag[HK[Option, Int]]
Run Code Online (Sandbox Code Playgroud)

这可能吗?我试过了

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]]
Run Code Online (Sandbox Code Playgroud)

但是由于显而易见的原因(在第一种情况下F[_]是存在类型而不是更高级的类型,在第二种TypeTag[F]情况下不能编译),它们都不起作用.

我怀疑答案是"这是不可能的",但如果不是,那将非常高兴.

编辑:我们目前使用WeakTypeTag如下(略微简化):

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]
}
Run Code Online (Sandbox Code Playgroud)

如果我们替换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]]
  }
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ich 4

这符合您的目的吗?

def tagHK[F[_], A](implicit tt: TypeTag[HK[F, A]]) = tt
Run Code Online (Sandbox Code Playgroud)

与使用隐式参数分别获取TypeTagforFA然后组合它们相反,您可以直接向编译器请求您想要的标记。这将根据需要通过您的测试用例:

tagHK[Option, Int] == typeTag[HK[Option, Int]] //true
Run Code Online (Sandbox Code Playgroud)

或者,如果您有一个实例,TypeTag[A]您可以尝试:

object HK {
    def apply[F[_]] = new HKTypeProvider[F]
    class HKTypeProvider[F[_]] {
        def get[A](tt: TypeTag[A])(implicit hktt: TypeTag[HK[F, A]]) = hktt
    }
}
Run Code Online (Sandbox Code Playgroud)

允许您执行以下操作:

val myTT = typeTag[Int]
HK[Option].get(myTT) == typeTag[HK[Option, Int]] //true
Run Code Online (Sandbox Code Playgroud)