scalafunctional-programmingtypeshigher-kinded-types

Can we define a higher-kinded type-level identity function in Scala?


In Scala we can define the type-level identity function for lower-kinded types like so,

type Id[A] = A

Can we also define something similar for higher-kinded types? Ie. can we fill in the blanks in,

type HKId[A[...]] = ...

so that something similar to HKId[List] gets us back to the List type constructor?

Binding of free names in things like,

type Foo[X] = List[X]
val l : Foo[Int] = List(1, 2, 3)

Might lead us to expect that a higher-kinded type-level identity would look like,

type HKId[A[X]] = A[X]

but scalac complains that type X is not found on the RHS.

Is there some clever encoding that will do the trick? Or is it just not possible right now?


Solution

  • It seems a bit unfair to snatch the correct answer away from @retronym, but it looks like we can get a little closer to the kind of solution I was after,

    scala> type HKId[A[_]] = { type λ[X] = A[X] }
    defined type alias HKId
    
    scala> def foo[C[_]] : C[Int] = null.asInstanceOf
    foo: [C[_]]=> C[Int]
    
    scala> foo[List]
    res0: List[Int] = null
    
    scala> foo[HKId[List]#λ]
    res1: List[Int] = null
    

    I'm not sure why this seems obvious now but wasn't obvious a year ago ... maybe because we've all got a lot more used to seeing type lambdas since then.