Подтвердить что ты не робот

Построение TypeTags более высокосортных типов

Учитывая простой параметризованный тип типа 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] не компилируется).

Я подозреваю, что ответ "невозможно", но был бы очень доволен, если это не так.

EDIT: в настоящее время мы используем 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]
}

Все это отлично работает, если мы заменим 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]]
  }
}
4b9b3361

Ответ 1

Это служит вашим целям?

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

В отличие от использования неявного параметра для получения TypeTag для F и A отдельно, а затем их составления, вы можете напрямую запросить тег, который вы хотите получить от компилятора. Это передаст ваш тестовый пример по желанию:

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