cs-4400-sp26

Lecture 8: Simply-Typed Lambda Calculus

Lecture outline

Review: IfLang type system

Typing rules: Judgment form: e : t

--------- ty/tt      ----------- ty/ff    ------------------ ty/n
tt : Bool             ff : Bool            (num n) : Number

e1 : Number     e2 : Number
--------------------------- ty/+
   (e1 + e2) : Number
   
e : Bool     e1 : t     e2 : t
------------------------------- ty/if
   if e then e1 else e2 : t

Concept: these rules are syntax-directed. That is, there is exactly one rule matching every syntactic form in the language.

IfLang Soundness

“Well-typed programs don’t go wrong” => “Well-typed programs evaluate to a value of the same type” => If e : t, then e ==> v and v : t

Proof: by induction over the derivation of e : t

Look at each inference rule for e ==> v one by one:

Scope Checking

Jugment: Γ ⊢ e ok – means e is well-scoped, i.e. all of its free variables are in Γ.

Examples:

Goal property:

x ∈ Γ
--------- ok/var
Γ ⊢ x ok


---------------- ok/num
Γ ⊢ (num n) ok


Γ ⊢ e1 ok    Γ, x ⊢ e2 ok
----------------------------- ok/let
Γ ⊢ (let x = e1 in e2) ok

Exercise: check the good/bad example above.

STLC

Type errors we want to rule out:

Inference rules*

Values: v ::= num n | λx.e

Types: t ::= Num | t -> t

Expressions: e ::= num n | e + e | λx.e | e e | x

x : t ∈ Γ
------------ ty/var
Γ ⊢ x : t

------------------ ty/num
Γ ⊢ (num n) : Num


Γ ⊢ e1 : Num    Γ ⊢ e2 : Num
------------------------------- ty/+
Γ ⊢ e1 + e2  :  Num


Γ, x : t ⊢ e : s
--------------------- ty/λ
Γ ⊢ λx.e  :  t -> s


Γ ⊢ e1 : t -> s     Γ ⊢ e2 : t1
--------------------------------- ty/app
Γ ⊢ (e1 e2) : s

Exercises

If we write a small step semantics, we can prove something easier:

If e : t, then either e is a value of type t, or e can take a step to some e' : t.

This formulation is sometimes broken out into two lemmas, known as progress and preservation:

Some lemmas, representative of key ideas in designing type systems:

Implementing STLC

Take a look at the rules and think about how to implement them.

Can we write a type checker?

Can we write a type synthesizer?

There are a lot of approaches to resolving this, but one way is to ask the programmer to provide type annotations in certain places.

In particular, if we ask λ expressions to annotate their input type, we can write a type synthesizer.

See lec8-stlc.rkt for code.

Further reading

Frank Pfenning on Simple Types