3 # System F and recursive types
5 In the simply-typed lambda calculus, we write types like <code>σ
6 -> τ</code>. This looks like logical implication. We'll take
7 that resemblance seriously when we discuss the Curry-Howard
8 correspondence. In the meantime, note that types respect modus
12 Expression Type Implication
13 -----------------------------------
14 fn α -> β α ⊃ β
16 ------ ------ --------
17 (fn arg) β β
20 The implication in the right-hand column is modus ponens, of course.
22 System F was discovered by Girard (the same guy who invented Linear
23 Logic), but it was independently proposed around the same time by
24 Reynolds, who called his version the *polymorphic lambda calculus*.
25 (Reynolds was also an early player in the development of
28 System F enhances the simply-typed lambda calculus with abstraction
29 over types. Normal lambda abstraction abstracts (binds) an expression
30 (a term); type abstraction abstracts (binds) a type.
32 In order to state System F, we'll need to adopt the
33 notational convention (which will last throughout the rest of the
34 course) that "<code>x:α</code>" represents an expression `x`
35 whose type is <code>α</code>.
37 Then System F can be specified as follows (choosing notation that will
38 match up with usage in O'Caml, whose type system is based on System F):
42 types τ ::= c | 'a | τ1 -> τ2 | ∀'a. τ
43 expressions e ::= x | λx:τ. e | e1 e2 | Λ'a. e | e [τ]
45 In the definition of the types, "`c`" is a type constant. Type
46 constants play the role in System F that base types play in the
47 simply-typed lambda calculus. So in a lingusitics context, type
48 constants might include `e` and `t`. "`'a`" is a type variable. The
49 tick mark just indicates that the variable ranges over types rather
50 than over values; in various discussion below and later, type variable
51 can be distinguished by using letters from the greek alphabet
52 (α, β, etc.), or by using capital roman letters (X, Y,
53 etc.). "`τ1 -> τ2`" is the type of a function from expressions of
54 type `τ1` to expressions of type `τ2`. And "`∀'a. τ`" is called a
55 universal type, since it universally quantifies over the type variable
56 `'a`. You can expect that in `∀'a. τ`, the type `τ` will usually
57 have at least one free occurrence of `'a` somewhere inside of it.
59 In the definition of the expressions, we have variables "`x`" as usual.
60 Abstracts "`λx:τ. e`" are similar to abstracts in the simply-typed lambda
61 calculus, except that they have their shrug variable annotated with a
62 type. Applications "`e1 e2`" are just like in the simply-typed lambda calculus.
64 In addition to variables, abstracts, and applications, we have two
65 additional ways of forming expressions: "`Λ'a. e`" is called a *type
66 abstraction*, and "`e [τ]`" is called a *type application*. The idea
67 is that <code>Λ</code> is a capital <code>λ</code>: just
68 like the lower-case <code>λ</code>, <code>Λ</code> binds
69 variables in its body, except that unlike <code>λ</code>,
70 <code>Λ</code> binds type variables instead of expression
71 variables. So in the expression
73 <code>Λ 'a (λ x:'a . x)</code>
75 the <code>Λ</code> binds the type variable `'a` that occurs in
76 the <code>λ</code> abstract. Of course, as long as type
77 variables are carefully distinguished from expression variables (by
78 tick marks, Grecification, or capitalization), there is no need to
79 distinguish expression abstraction from type abstraction by also
80 changing the shape of the lambda.
82 The expression immediately below is a polymorphic version of the
83 identity function. It defines one general identity function that can
84 be adapted for use with expressions of any type. In order to get it
85 ready to apply this identity function to, say, a variable of type
86 boolean, just do this:
88 <code>(Λ 'a (λ x:'a . x)) [t]</code>
90 This type application (where `t` is a type constant for Boolean truth
91 values) specifies the value of the type variable `'a`. Not
92 surprisingly, the type of this type application is a function from
95 <code>((Λ 'a (λ x:'a . x)) [t]): (b -> b)</code>
97 Likewise, if we had instantiated the type variable as an entity (base
98 type `e`), the resulting identity function would have been a function
101 <code>((Λ 'a (λ x:'a . x)) [e]): (e -> e)</code>
103 Clearly, for any choice of a type `'a`, the identity function can be
104 instantiated as a function from expresions of type `'a` to expressions
105 of type `'a`. In general, then, the type of the uninstantiated
106 (polymorphic) identity function is
108 <code>(Λ 'a (λ x:'a . x)): (∀ 'a . 'a -> 'a)</code>
113 We saw that the predecessor function couldn't be expressed in the
114 simply-typed lambda calculus. It *can* be expressed in System F,
115 however. Here is one way, coded in
116 [[Benjamin Pierce's type-checker and evaluator for
117 System F|http://www.cis.upenn.edu/~bcpierce/tapl/index.html]] (the
118 relevant evaluator is called "fullpoly"):
120 N = All X . (X->X)->X->X;
121 Pair = (N -> N -> N) -> N;
122 let zero = lambda X . lambda s:X->X . lambda z:X. z in
123 let fst = lambda x:N . lambda y:N . x in
124 let snd = lambda x:N . lambda y:N . y in
125 let pair = lambda x:N . lambda y:N . lambda z:N->N->N . z x y in
126 let suc = lambda n:N . lambda X . lambda s:X->X . lambda z:X . s (n [X] s z) in
127 let shift = lambda p:Pair . pair (suc (p fst)) (p fst) in
128 let pre = lambda n:N . n [Pair] shift (pair zero zero) snd in
130 pre (suc (suc (suc zero)));
132 We've truncated the names of "suc(c)" and "pre(d)", since those are
133 reserved words in Pierce's system. Note that in this code, there is
134 no typographic distinction between ordinary lambda and type-level
135 lambda, though the difference is encoded in whether the variables are
136 lower case (for ordinary lambda) or upper case (for type-level
139 The key to the extra expressive power provided by System F is evident
140 in the typing imposed by the definition of `pre`. The variable `n` is
141 typed as a Church number, i.e., as `All X . (X->X)->X->X`. The type
142 application `n [Pair]` instantiates `n` in a way that allows it to
143 manipulate ordered pairs: `n [Pair]: (Pair->Pair)->Pair->Pair`. In
144 other words, the instantiation turns a Church number into a
145 pair-manipulating function, which is the heart of the strategy for
146 this version of predecessor.
148 Could we try to build a system for doing Church arithmetic in which
149 the type for numbers always manipulated ordered pairs? The problem is
150 that the ordered pairs we need here are pairs of numbers. If we tried
151 to replace the type for Church numbers with a concrete (simple) type,
152 we would have to replace each `X` with the type for Pairs, `(N -> N ->
153 N) -> N`. But then we'd have to replace each of these `N`'s with the
154 type for Church numbers, `(X -> X) -> X -> X`. And then we'd have to
155 replace each of these `X`'s with... ad infinitum. If we had to choose
156 a concrete type built entirely from explicit base types, we'd be
159 [See Benjamin C. Pierce. 2002. *Types and Programming Languages*, MIT
165 In fact, unlike in the simply-typed lambda calculus,
166 it is even possible to give a type for ω in System F.
168 <code>ω = lambda x:(All X. X->X) . x [All X . X->X] x</code>
170 In order to see how this works, we'll apply ω to the identity
173 <code>ω id ==</code>
175 (lambda x:(All X . X->X) . x [All X . X->X] x) (lambda X . lambda x:X . x)
177 Since the type of the identity function is `(All X . X->X)`, it's the
178 right type to serve as the argument to ω. The definition of
179 ω instantiates the identity function by binding the type
180 variable `X` to the universal type `All X . X->X`. Instantiating the
181 identity function in this way results in an identity function whose
182 type is (in some sense, only accidentally) the same as the original
183 fully polymorphic identity function.
185 So in System F, unlike in the simply-typed lambda calculus, it *is*
186 possible for a function to apply to itself!
188 Does this mean that we can implement recursion in System F? Not at
189 all. In fact, despite its differences with the simply-typed lambda
190 calculus, one important property that System F shares with the
191 simply-typed lambda calculus is that they are both strongly
192 normalizing: *every* expression in either system reduces to a normal
193 form in a finite number of steps.
195 Not only does a fixed-point combinator remain out of reach, we can't
196 even construct an infinite loop. This means that although we found a
197 type for ω, there is no general type for Ω ≡ ω
198 ω. Furthermore, it turns out that no Turing complete system can
199 be strongly normalizing, from which it follows that System F is not
206 OCaml has type inference: the system can often infer what the type of
207 an expression must be, based on the type of other known expressions.
209 For instance, if we type
213 The system replies with
215 val f : int -> int = <fun>
217 Since `+` is only defined on integers, it has type
220 - : int -> int -> int = <fun>
222 The parentheses are there to turn off the trick that allows the two
223 arguments of `+` to surround it in infix (for linguists, SOV) argument
229 In general, tuples with one element are identical to their one
235 though OCaml, like many systems, refuses to try to prove whether two
236 functional objects may be identical:
239 Exception: Invalid_argument "equal: functional value".
243 [Note: There is a limited way you can compare functions, using the
244 `==` operator instead of the `=` operator. Later when we discuss mutation,
245 we'll discuss the difference between these two equality operations.
246 Scheme has a similar pair, which they name `eq?` and `equal?`. In Python,
247 these are `is` and `==` respectively. It's unfortunate that OCaml uses `==` for the opposite operation that Python and many other languages use it for. In any case, OCaml will accept `(f) == f` even though it doesn't accept
248 `(f) = f`. However, don't expect it to figure out in general when two functions
249 are equivalent. (That question is not Turing computable.)
251 # (f) == (fun x -> x + 3);;
254 Here OCaml says (correctly) that the two functions don't stand in the `==` relation, which basically means they're not represented in the same chunk of memory. However as the programmer can see, the functions are extensionally equivalent. The meaning of `==` is rather weird.]
258 Booleans in OCaml, and simple pattern matching
259 ----------------------------------------------
261 Where we would write `true 1 2` in our pure lambda calculus and expect
262 it to evaluate to `1`, in OCaml boolean types are not functions
263 (equivalently, they're functions that take zero arguments). Instead, selection is
264 accomplished as follows:
266 # if true then 1 else 2;;
269 The types of the `then` clause and of the `else` clause must be the
272 The `if` construction can be re-expressed by means of the following
273 pattern-matching expression:
275 match <bool expression> with true -> <expression1> | false -> <expression2>
279 # match true with true -> 1 | false -> 2;;
284 # match 3 with 1 -> 1 | 2 -> 4 | 3 -> 9;;
290 All functions in OCaml take exactly one argument. Even this one:
292 # let f x y = x + y;;
296 Here's how to tell that `f` has been curry'd:
299 - : int -> int = <fun>
301 After we've given our `f` one argument, it returns a function that is
302 still waiting for another argument.
304 There is a special type in OCaml called `unit`. There is exactly one
305 object in this type, written `()`. So
310 Just as you can define functions that take constants for arguments
316 you can also define functions that take the unit as its argument, thus
319 val f : unit -> int = <fun>
321 Then the only argument you can possibly apply `f` to that is of the
322 correct type is the unit:
327 Now why would that be useful?
329 Let's have some fun: think of `rec` as our `Y` combinator. Then
331 # let rec f n = if (0 = n) then 1 else (n * (f (n - 1)));;
332 val f : int -> int = <fun>
336 We can't define a function that is exactly analogous to our ω.
337 We could try `let rec omega x = x x;;` what happens?
339 [Note: if you want to learn more OCaml, you might come back here someday and try:
342 val id : 'a -> 'a = <fun>
343 # let unwrap (`Wrap a) = a;;
344 val unwrap : [< `Wrap of 'a ] -> 'a = <fun>
345 # let omega ((`Wrap x) as y) = x y;;
346 val omega : [< `Wrap of [> `Wrap of 'a ] -> 'b as 'a ] -> 'b = <fun>
347 # unwrap (omega (`Wrap id)) == id;;
349 # unwrap (omega (`Wrap omega));;
350 <Infinite loop, need to control-c to interrupt>
352 But we won't try to explain this now.]
355 Even if we can't (easily) express omega in OCaml, we can do this:
357 # let rec blackhole x = blackhole x;;
359 By the way, what's the type of this function?
361 If you then apply this `blackhole` function to an argument,
365 the interpreter goes into an infinite loop, and you have to type control-c
368 Oh, one more thing: lambda expressions look like this:
372 # (fun x -> x) true;;
375 (But `(fun x -> x x)` still won't work.)
377 You may also see this:
379 # (function x -> x);;
382 This works the same as `fun` in simple cases like this, and slightly differently in more complex cases. If you learn more OCaml, you'll read about the difference between them.
384 We can try our usual tricks:
386 # (fun x -> true) blackhole;;
389 OCaml declined to try to fully reduce the argument before applying the
390 lambda function. Question: Why is that? Didn't we say that OCaml is a call-by-value/eager language?
392 Remember that `blackhole` is a function too, so we can
393 reverse the order of the arguments:
395 # blackhole (fun x -> true);;
399 Now consider the following variations in behavior:
401 # let test = blackhole blackhole;;
402 <Infinite loop, need to control-c to interrupt>
404 # let test () = blackhole blackhole;;
405 val test : unit -> 'a = <fun>
408 - : unit -> 'a = <fun>
411 <Infinite loop, need to control-c to interrupt>
413 We can use functions that take arguments of type `unit` to control
414 execution. In Scheme parlance, functions on the `unit` type are called
415 *thunks* (which I've always assumed was a blend of "think" and "chunk").
417 Question: why do thunks work? We know that `blackhole ()` doesn't terminate, so why do expressions like:
419 let f = fun () -> blackhole ()
424 Bottom type, divergence
425 -----------------------
427 Expressions that don't terminate all belong to the **bottom type**. This is a subtype of every other type. That is, anything of bottom type belongs to every other type as well. More advanced type systems have more examples of subtyping: for example, they might make `int` a subtype of `real`. But the core type system of OCaml doesn't have any general subtyping relations. (Neither does System F.) Just this one: that expressions of the bottom type also belong to every other type. It's as if every type definition in OCaml, even the built in ones, had an implicit extra clause:
429 type 'a option = None | Some of 'a;;
430 type 'a option = None | Some of 'a | bottom;;
432 Here are some exercises that may help better understand this. Figure out what is the type of each of the following:
440 let rec blackhole x = blackhole x in blackhole;;
442 let rec blackhole x = blackhole x in blackhole 1;;
444 let rec blackhole x = blackhole x in fun (y:int) -> blackhole y y y;;
446 let rec blackhole x = blackhole x in (blackhole 1) + 2;;
448 let rec blackhole x = blackhole x in (blackhole 1) || false;;
450 let rec blackhole x = blackhole x in 2 :: (blackhole 1);;
452 By the way, what's the type of this:
454 let rec blackhole (x:'a) : 'a = blackhole x in blackhole
457 Back to thunks: the reason you'd want to control evaluation with
458 thunks is to manipulate when "effects" happen. In a strongly
459 normalizing system, like the simply-typed lambda calculus or System F,
460 there are no "effects." In Scheme and OCaml, on the other hand, we can
461 write programs that have effects. One sort of effect is printing.
462 Another sort of effect is mutation, which we'll be looking at soon.
463 Continuations are yet another sort of effect. None of these are yet on
464 the table though. The only sort of effect we've got so far is
465 *divergence* or non-termination. So the only thing thunks are useful
466 for yet is controlling whether an expression that would diverge if we
467 tried to fully evaluate it does diverge. As we consider richer
468 languages, thunks will become more useful.