Exercise 5.15 The typing rules for Mini-ML in Section 2.5 are not a realistic basis for an implementation, since they require e_{1} in an expression of the form let name u = e_{1} in e_{2} to be re-checked at every occurrence of u in e_{2}. This is because we may need to assign different types to e_{1} for different occurrences of u.

Fortunately, all the different types for an expression e can be seen as instances of a most general type schema for e. In this exercise we explore an alternative formulation of Mini-ML which uses explicit type schemas.

Types τ ::= nat | τ_{1} × τ_{2} | τ_{1} → τ_{2} | α
Type Schemas σ ::= τ | ∀α. σ

Type schemas σ are related to types τ through instantiation, written as σ ⪯ τ. This judgment is defined by

\frac{inst tp}{τ ⪯ τ} \begin{aligned}[τ′/α]σ ⪯ τ \\ & inst all. \\ ∀α. σ ⪯ τ \end{aligned}

We modify the judgment Δ ▷ e : τ and add a second judgment, Δ ▷▷ e : σ stating that e has type schema σ. The typing rule for let name now no longer employs substitution, but refers to a schematic type for the definition. It must therefore be possible to assign type schemas to variables which are instantiated when we need an actual type for a variable.

Δ ▷▷ e_{1} : σ_{1} Δ, x:σ_{1} ▷ e_{2} : τ_{2} tp letn

Δ ▷ let name x = e_{1} in e_{2} : τ_{2}

\begin{aligned}Δ(x) = σ σ ⪯ τ \\ & tp var \\ Δ ▷ x : τ \end{aligned}

Type schemas can be derived for expressions by means of quantifying over free type variables.

Δ ▷ e : τ ; tpsc tp ; Δ ▷▷ e : τ Δ ▷▷ e : σ ; tpsc all^{α} ; Δ ▷▷ e : ∀α. σ

Here the premiss of the tpsc all^{α} rule must be parametric in α, that is, α must not occur free in the context Δ.

In the proofs and implementations below you may restrict yourself to the fragment of the language with functions and let name, since the changes are orthogonal to the other constructs of the language.

1. Give an example which shows why the restriction on the tpsc all rule is necessary.

2. Prove type preservation for this formulation of Mini-ML. Carefully write out and prove any substitution lemmas you might need, but you may take weakening and exchange for granted.

3. State the theorem which asserts the equivalence of the new typing rules when compared to the formulation in Section 2.5.

4. Prove the easy direction of the theorem in item 3. Can you conjecture the critical lemma for the opposite direction?

5. Implement type schemas, schematic instantiation, and the new typing judgments in Elf.

6. Unlike our first implementation, the new typing rules do not directly provide an implementation of type inference for Mini-ML in Elf. Show the difficulty by means of an example.

7. Implement the proof of type preservation from item 2 in Elf.

8. Implement one direction of the equivalence proof from item 3 in Elf.