There are claims that Scala’s type system is Turing complete. My questions are:
-
Is there a formal proof for this?
-
How would a simple computation look like in the Scala type system?
-
Is this of any benefit to Scala – the language? Is this making Scala more “powerful” in some way compared languages without a Turing complete type system?
I guess this applies to languages and type systems in general.
There is a blog post somewhere with a type-level implementation of the SKI combinator calculus, which is known to be Turing-complete.
Turing-complete type systems have basically the same benefits and drawbacks that Turing-complete languages have: you can do anything, but you can prove very little. In particular, you cannot prove that you will actually eventually do something.
One example of type-level computation are the new type-preserving collection transformers in Scala 2.8. In Scala 2.8, methods like
map,filterand so on are guaranteed to return a collection of the same type that they were called on. So, if youfilteraSet[Int], you get back aSet[Int]and if youmapaList[String]you get back aList[Whatever the return type of the anonymous function is].Now, as you can see,
mapcan actually transform the element type. So, what happens if the new element type cannot be represented with the original collection type? Example: aBitSetcan only contain fixed-width integers. So, what happens if you have aBitSet[Short]and you map each number to its string representation?The result would be a
BitSet[String], but that’s impossible. So, Scala chooses the most derived supertype ofBitSet, which can hold aString, which in this case is aSet[String].All of this computation is going on during compile time, or more precisely during type checking time, using type-level functions. Thus, it is statically guaranteed to be type-safe, even though the types are actually computed and thus not known at design time.