Ideas of Week5
Type Inference
SML has a static type system, i.e., it determines all the types for its bindings before ever executing the program. But unlike most statically typed programming languages, like C, Java, SML is implicitly typed. We don’t write down the type of our bindings ever since Week3. Inside the SML is an algorithm called type inference that figures out the type of the bindings for us. It may sound magic for the first time, but in this week, Dan explained this mechanics for us.
The central idea of this algorithm is do assumptions and deductions as we go. It exams the bindings from top to bottom and every time a new thing comes up it first assumes that it is a new type and then infers its type by collecting facts associated with it. Here is an example:1
2
3
4fun f x =
let val (y, z) = x in
(abs y) + z
end
The whole inference process goes like this:
- Looking at the first line, this is a function binding. So
f
has typeT1->T2
for being a function. Andx
has typeT1
for being the only parameter off
. - Looking at the second line,
x
must have typeT3*T4
for the pattern matching to type check. Also,y
has typeT3
andz
has typeT4
. - Examing the third line. We know from the standard library
abs
has typeint->int
. SoT3=int
.z
must also have typeint
because onlyint
can be added toint
. SoT4=int
. - Looking at the last line, the whole
let
expression ends with an addition. So the type of thelet
expression isint
. Thus the type of the returned value off
isint
. - Combining all the facts together and concluding that
f
has typeint*int->int
.
Now type inference may seem more easy and simple. But to have type inference in a programming language requires delicate design. SML is well designed to have a good type inference algorithm. Some of the programming languages does not even have a feasible type inference algorithm. A feasible type inference algorithm must do the following three things:
- Always terminate
- Accept all the programs that type check and give the right type
- Reject all the programs that does not type check
The question of how difficult the type inference algorithm is does not have a clear relation with how permissive the type system of the language is. For example, the type system that accepts everything and the type system that rejects everything are both easy to type check and type infer. Actually, to make the type inference in SML more difficult, we only need small modification to the type system of SML.
- If we admit subtyping(e.g., if every triple can also be a pair), the type inference will be much more difficult because we cannot reach the conclusion
x
has typeT1*T2
with the pattern matching(y, z) = x
.x
may have two, three or more fields. - If we disallow polymophic types, the type inference will also be more difficult because the type inference algorithm has to choose one concrete type which depends on the use of the binding.