10

给定一个简单的参数化类型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]]
  }
}
4

1 回答 1

4

这是否符合您的目的?

def tagHK[F[_], A](implicit tt: TypeTag[HK[F, A]]) = tt

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

tagHK[Option, Int] == typeTag[HK[Option, Int]] //true

或者,如果您有一个实例,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
    }
}

允许您执行以下操作:

val myTT = typeTag[Int]
HK[Option].get(myTT) == typeTag[HK[Option, Int]] //true
于 2015-04-27T13:59:57.463 回答