## Revisiting higher-rank impredicative polymorphism in Scala

I've been meaning to write this up for a while, but it seems like there has always been something else I really ought to be doing. So I expect this will be a bit more terse than I might like. Anyway, when I wrote about encoding higher-rank universal quantification in Scala back in March, I used a rather elaborate scheme involving the use of Scala's first-class existential quantifiers. While this was the point of the exercise, surprisingly, no one called me on the fact that if you just want higher-rank impredicative polymorphism in Scala, there is a much simpler encoding. Maybe it was obvious to everyone or no one read closely enough to think of raising the issue. So today, I'll explain the better way to encode them.

First we can define an infinite family of traits to represent n-ary universal quantification, much like Scala represents n-ary functions types:

``` trait Univ1[Bound1,Body[_]] {
def Apply[T1<:Bound1] : Body[T1]
}
trait Univ2[Bound1,Bound2,Body[_,_]] {
def Apply[T1<:Bound1,T2<:Bound2] : Body[T1,T2]
}
// ... so on for N > 2
```

Really, the key to this encoding is the use of higher-kinded quantification to encode the binding structure of the quantifier.

Now it is possible to write some examples similar to what I gave previously, but more concisely:

``` object Test extends Application {
def id[T](x : T) = x
type Id[T] = T => T
val id = new Univ1[Any,Id]
{ def Apply[T <: Any] : Id[T] = id[T] _ }
val idString = id.Apply[String]
val idStringList = id.Apply[List[String]]
println(idString("Foo"))
println(idStringList(List("Foo", "Bar", "Baz")))
type Double[T] = T => (T, T)
val double = new Univ1[Any,Double]
{ def Apply[T <: Any] : Double[T] = (x : T) => (x, x) }
val doubleString = double.Apply[String]
val doubleStringList = double.Apply[List[String]]
println(doubleString("Foo"))
println(doubleStringList(List("Foo", "Bar", "Baz")))
}
```

As I mentioned previously, this example would be much improved by support for anonymous type functions in Scala. I am pretty sure Scala will eventually support them, as they would not require any deep changes in the implementation. They could be just implemented by desugaring to a higher-kinded type alias with a fresh name, but depending on when that desugaring is performed, it is possible that it would result in poor error messages. Supporting curried type functions is also quite desirable, but given my current knowledge of the internals, that seems like adding them will require some more elaborate changes.

I think Vincent Cremet was the first person to suggest this sort of encoding, and I vaguely recall reading about it on one of the Scala mailing lists, but I could not find the message after a little bit of time spent searching.