Semantics of Programming Languages Lecture 9
Semantics of Programming Languages Lecture 9
Things go wrong
I tt λx .0
I if λx .x = 1 then 0 else ff
Typing:
A static analysis to avoid runtime errors
Simple types
σ1 → σ2 → . . . . . . σk → base k ≥0
Typing judgements
Γ`M:σ
Type environment Γ:
Γ ::= | Γ, x : σ
Environment lookup:
(ty-look1) (ty-look2)
Γ ` x 2 : σ1
x1 6= x2
Γ, x : σ ` x : σ Γ, x1 : σ1 ` x2 : σ2
Γ ` n : int
(ty-bool) (ty-bool)
Γ ` tt : bool Γ ` ff : bool
(ty-i−op) (ty-b−op)
Γ ` F1 : int Γ ` F2 : int Γ ` F1 : bool Γ ` F1 : bool
Γ ` F1 op F2 : int Γ ` F1 bop F2 : bool
(ty-le)
Γ ` F1 : int Γ ` F2 : int
Γ ` F1 < F2 : bool
(ty-eq)
Γ ` F1 : base Γ ` F2 : base
Γ ` F1 = F2 : bool
(ty-if)
Γ ` B : bool
Γ ` F1 : σ Γ ` F2 : σ
Γ ` if B then F1 else F2 : σ
Typing functions
(ty-abs)
Γ, x : σ1 ` M : σ2
Γ ` λx .M : σ1 → σ2
(ty-app)
Γ ` M : σ1 → σ2 , Γ ` N : σ1
Γ ` M N : σ2
Example typing
(ty-look) (ty-look)
Γxf ` f : int → int Γxf ` x : int
(ty-app) (ty-int)
Γxf ` f (x) : int Γxf ` 1 : int
(ty-add)
x : int, f : int → int ` f (x) + 1 : int
(ty-abs)
x : int ` λf .f (x) + 1 : (int → int) → int
(ty-abs)
ε ` λx .λf .f (x) + 1 : int → (int → int) → int
Sanity checks
I Repetition: Γ1 , x : σ1 , Γ2 , x : σ2 , Γ3 ` M : σ implies
Γ1 , Γ2 , x : σ2 , Γ3 ` M : σ
I Strengthening:
If x is not in fv(M) then Γ1 , x : σx , Γ2 ` M : σ implies
Γ1 , Γ2 ` M : σ.
I Weakening:
I Γ ` M : σ implies x : σx , Γ ` M : σ
I Γ ` M : σ implies Γ, x : σx ` M : σ, provided x does not occur in M.
I Permutation: Γ1 , x : σx , y : σy , Γ2 ` M : σ implies
Γ1 , y : σy , x : σx , Γ2 ` M : σ, provided x is different than y .
Progress:
Suppose M is a program closed term and ` M : σ Then either:
I M is a value
I or M → N for some N
Proof by induction on ` M
Preservation:
If Γ ` M : σ and M → N then Γ ` N : σ
Proof by Rule Induction on M → N
Requires Substitution Property for typing derivations
Typing Lambda Draft April 16, 2013
Simple types Explicit types Fixpoint operators
Substitution Property
M ∈ Lambdafix ::= . . .
| λx : σ .M | M1 M2
| fix.M
Semantics:
(l-fix)
fix.M →l M(fix.M)
Typing:
(ty-fix)
Γ`M:σ→σ
Γ ` fix.M : σ
Example
fix.F 1 →l F (fix.F ) 1
→l (λx .if x = 0 then 1 else fix.F (x − 1)) 1
→l if 1 = 0 then 1 else fix.F (1 − 1)
→∗l fix.F (1 − 1)
→l F (fix.F ) (1 − 1)
→l (λx .if x = 0 then 1 else fix.F (x − 1)) (1 − 1)
→l if (1 − 1) = 0 then 1 else fix.F ((1 − 1) − 1)
→∗ 1
fix.F 1 →e F (fix.F ) 1
→e F (F fix.F ) 1
→e . . .
→e F (F (F . . . fix.F ) . . .) 1
Eager fixpoint
M ≈sem λx .M x
provided:
I x is fresh to M
I M has a function type σ1 → σ2
Semantics: Typing:
(l-cbv.fix) (ty-cbv.fix)
fixcbv .M → M(λx .fixcbv .M x) Γ`M:σ→σ
Γ ` fixcbv .M : σ
Example: Eager