1 # System F and recursive types
3 In the simply-typed lambda calculus, we write types like <code>σ
4 -> τ</code>. This looks like logical implication. We'll take
5 that resemblance seriously when we discuss the Curry-Howard
6 correspondence. In the meantime, note that types respect modus
10 Expression Type Implication
11 -----------------------------------
12 fn α -> β α ⊃ β
14 ------ ------ --------
15 (fn arg) β β
18 The implication in the right-hand column is modus ponens, of course.
20 System F was discovered by Girard (the same guy who invented Linear
21 Logic), but it was independently proposed around the same time by
22 Reynolds, who called his version the *polymorphic lambda calculus*.
23 (Reynolds was also an early player in the development of
26 System F enhances the simply-typed lambda calculus with abstraction
27 over types. Normal lambda abstraction abstracts (binds) an expression
28 (a term); type abstraction abstracts (binds) a type.
30 In order to state System F, we'll need to adopt the
31 notational convention (which will last throughout the rest of the
32 course) that "<code>x:α</code>" represents an expression `x`
33 whose type is <code>α</code>.
35 Then System F can be specified as follows (choosing notation that will
36 match up with usage in O'Caml, whose type system is based on System F):
40 types τ ::= c | 'a | τ1 -> τ2 | ∀'a. τ
41 expressions e ::= x | λx:τ. e | e1 e2 | Λ'a. e | e [τ]
43 In the definition of the types, "`c`" is a type constant. Type
44 constants play the role in System F that base types play in the
45 simply-typed lambda calculus. So in a lingusitics context, type
46 constants might include `e` and `t`. "`'a`" is a type variable. The
47 tick mark just indicates that the variable ranges over types rather
48 than over values; in various discussion below and later, type variable
49 can be distinguished by using letters from the greek alphabet
50 (α, β, etc.), or by using capital roman letters (X, Y,
51 etc.). "`τ1 -> τ2`" is the type of a function from expressions of
52 type `τ1` to expressions of type `τ2`. And "`∀'a. τ`" is called a
53 universal type, since it universally quantifies over the type variable
54 `'a`. You can expect that in `∀'a. τ`, the type `τ` will usually
55 have at least one free occurrence of `'a` somewhere inside of it.
57 In the definition of the expressions, we have variables "`x`" as usual.
58 Abstracts "`λx:τ. e`" are similar to abstracts in the simply-typed lambda
59 calculus, except that they have their shrug variable annotated with a
60 type. Applications "`e1 e2`" are just like in the simply-typed lambda calculus.
62 In addition to variables, abstracts, and applications, we have two
63 additional ways of forming expressions: "`Λ'a. e`" is called a *type
64 abstraction*, and "`e [τ]`" is called a *type application*. The idea
65 is that <code>Λ</code> is a capital <code>λ</code>: just
66 like the lower-case <code>λ</code>, <code>Λ</code> binds
67 variables in its body, except that unlike <code>λ</code>,
68 <code>Λ</code> binds type variables instead of expression
69 variables. So in the expression
71 <code>Λ 'a (λ x:'a . x)</code>
73 the <code>Λ</code> binds the type variable `'a` that occurs in
74 the <code>λ</code> abstract. Of course, as long as type
75 variables are carefully distinguished from expression variables (by
76 tick marks, Grecification, or capitalization), there is no need to
77 distinguish expression abstraction from type abstraction by also
78 changing the shape of the lambda.
80 This expression is a polymorphic version of the identity function. It
81 defines one general identity function that can be adapted for use with
82 expressions of any type. In order to get it ready to apply this
83 identity function to, say, a variable of type boolean, just do this:
85 <code>(Λ 'a (λ x:'a . x)) [t]</code>
87 This type application (where `t` is a type constant for Boolean truth
88 values) specifies the value of the type variable `'a`. Not
89 surprisingly, the type of this type application is a function from
92 <code>((Λ 'a (λ x:'a . x)) [t]): (b -> b)</code>
94 Likewise, if we had instantiated the type variable as an entity (base
95 type `e`), the resulting identity function would have been a function
98 <code>((Λ 'a (λ x:'a . x)) [e]): (e -> e)</code>
100 Clearly, for any choice of a type `'a`, the identity function can be
101 instantiated as a function from expresions of type `'a` to expressions
102 of type `'a`. In general, then, the type of the uninstantiated
103 (polymorphic) identity function is
105 <code>(Λ 'a (λ x:'a . x)): (∀ 'a . 'a -> 'a)</code>
110 We saw that the predecessor function couldn't be expressed in the
111 simply-typed lambda calculus. It *can* be expressed in System F,
112 however. Here is one way, coded in
113 [[Benjamin Pierce's type-checker and evaluator for
114 System F|http://www.cis.upenn.edu/~bcpierce/tapl/index.html]] (the
115 relevant evaluator is called "fullpoly"):
117 N = All X . (X->X)->X->X;
118 Pair = (N -> N -> N) -> N;
119 let zero = lambda X . lambda s:X->X . lambda z:X. z in
120 let fst = lambda x:N . lambda y:N . x in
121 let snd = lambda x:N . lambda y:N . y in
122 let pair = lambda x:N . lambda y:N . lambda z:N->N->N . z x y in
123 let suc = lambda n:N . lambda X . lambda s:X->X . lambda z:X . s (n [X] s z) in
124 let shift = lambda p:Pair . pair (suc (p fst)) (p fst) in
125 let pre = lambda n:N . n [Pair] shift (pair zero zero) snd in
127 pre (suc (suc (suc zero)));
129 We've truncated the names of "suc(c)" and "pre(d)", since those are
130 reserved words in Pierce's system. Note that in this code, there is
131 no typographic distinction between ordinary lambda and type-level
132 lambda, though the difference is encoded in whether the variables are
133 lower case (for ordinary lambda) or upper case (for type-level
136 The key to the extra expressive power provided by System F is evident
137 in the typing imposed by the definition of `pre`. The variable `n` is
138 typed as a Church number, i.e., as `All X . (X->X)->X->X`. The type
139 application `n [Pair]` instantiates `n` in a way that allows it to
140 manipulate ordered pairs: `n [Pair]: (Pair->Pair)->Pair->Pair`. In
141 other words, the instantiation turns a Church number into a
142 pair-manipulating function, which is the heart of the strategy for
143 this version of predecessor.
145 But of course, the type `Pair` (in this simplified example) is defined
146 in terms of Church numbers. If we tried to replace the type for
147 Church numbers with a concrete (simple) type, we would have to replace
148 each `X` with `(N -> N -> N) -> N`. But then we'd have to replace
149 each `N` with `(X -> X) -> X -> X`. And then replace each `X`
150 with... ad infinitum. If we had to choose a concrete type built
151 entirely from explicit base types, we'd be unable to proceed.
153 [See Benjamin C. Pierce. 2002. *Types and Programming Languages*, MIT
159 In fact, unlike in the simply-typed lambda calculus,
160 it is even possible to give a type for ω in System F.
162 <code>ω = lambda x:(All X. X->X) . x [All X . X->X] x</code>
164 In order to see how this works, we'll apply ω to the identity
167 <code>ω id ==</code>
169 (lambda x:(All X . X->X) . x [All X . X->X] x) (lambda X . lambda x:X . x)
171 Since the type of the identity function is `(All X . X->X)`, it's the
172 right type to serve as the argument to ω. The definition of
173 ω instantiates the identity function by binding the type
174 variable `X` to the universal type `All X . X->X`. Instantiating the
175 identity function in this way results in an identity function whose
176 type is (in some sense, only accidentally) the same as the original
177 fully polymorphic identity function.
179 So in System F, unlike in the simply-typed lambda calculus, it *is*
180 possible for a function to apply to itself!
182 Does this mean that we can implement recursion in System F? Not at
183 all. In fact, despite its differences with the simply-typed lambda
184 calculus, one important property that System F shares with the
185 simply-typed lambda calculus is that they are both strongly
186 normalizing: *every* expression in either system reduces to a normal
187 form in a finite number of steps.
189 Not only does a fixed-point combinator remain out of reach, we can't
190 even construct an infinite loop. This means that although we found a
191 type for ω, there is no general type for Ω ≡ ω
192 ω. Furthermore, it turns out that no Turing complete system can
193 be strongly normalizing, from which it follows that System F is not
200 OCaml has type inference: the system can often infer what the type of
201 an expression must be, based on the type of other known expressions.
203 For instance, if we type
207 The system replies with
209 val f : int -> int = <fun>
211 Since `+` is only defined on integers, it has type
214 - : int -> int -> int = <fun>
216 The parentheses are there to turn off the trick that allows the two
217 arguments of `+` to surround it in infix (for linguists, SOV) argument
223 In general, tuples with one element are identical to their one
229 though OCaml, like many systems, refuses to try to prove whether two
230 functional objects may be identical:
233 Exception: Invalid_argument "equal: functional value".
237 [Note: There is a limited way you can compare functions, using the
238 `==` operator instead of the `=` operator. Later when we discuss mutation,
239 we'll discuss the difference between these two equality operations.
240 Scheme has a similar pair, which they name `eq?` and `equal?`. In Python,
241 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
242 `(f) = f`. However, don't expect it to figure out in general when two functions
243 are equivalent. (That question is not Turing computable.)
245 # (f) == (fun x -> x + 3);;
248 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.]
252 Booleans in OCaml, and simple pattern matching
253 ----------------------------------------------
255 Where we would write `true 1 2` in our pure lambda calculus and expect
256 it to evaluate to `1`, in OCaml boolean types are not functions
257 (equivalently, they're functions that take zero arguments). Instead, selection is
258 accomplished as follows:
260 # if true then 1 else 2;;
263 The types of the `then` clause and of the `else` clause must be the
266 The `if` construction can be re-expressed by means of the following
267 pattern-matching expression:
269 match <bool expression> with true -> <expression1> | false -> <expression2>
273 # match true with true -> 1 | false -> 2;;
278 # match 3 with 1 -> 1 | 2 -> 4 | 3 -> 9;;
284 All functions in OCaml take exactly one argument. Even this one:
286 # let f x y = x + y;;
290 Here's how to tell that `f` has been curry'd:
293 - : int -> int = <fun>
295 After we've given our `f` one argument, it returns a function that is
296 still waiting for another argument.
298 There is a special type in OCaml called `unit`. There is exactly one
299 object in this type, written `()`. So
304 Just as you can define functions that take constants for arguments
310 you can also define functions that take the unit as its argument, thus
313 val f : unit -> int = <fun>
315 Then the only argument you can possibly apply `f` to that is of the
316 correct type is the unit:
321 Now why would that be useful?
323 Let's have some fun: think of `rec` as our `Y` combinator. Then
325 # let rec f n = if (0 = n) then 1 else (n * (f (n - 1)));;
326 val f : int -> int = <fun>
330 We can't define a function that is exactly analogous to our ω.
331 We could try `let rec omega x = x x;;` what happens?
333 [Note: if you want to learn more OCaml, you might come back here someday and try:
336 val id : 'a -> 'a = <fun>
337 # let unwrap (`Wrap a) = a;;
338 val unwrap : [< `Wrap of 'a ] -> 'a = <fun>
339 # let omega ((`Wrap x) as y) = x y;;
340 val omega : [< `Wrap of [> `Wrap of 'a ] -> 'b as 'a ] -> 'b = <fun>
341 # unwrap (omega (`Wrap id)) == id;;
343 # unwrap (omega (`Wrap omega));;
344 <Infinite loop, need to control-c to interrupt>
346 But we won't try to explain this now.]
349 Even if we can't (easily) express omega in OCaml, we can do this:
351 # let rec blackhole x = blackhole x;;
353 By the way, what's the type of this function?
355 If you then apply this `blackhole` function to an argument,
359 the interpreter goes into an infinite loop, and you have to type control-c
362 Oh, one more thing: lambda expressions look like this:
366 # (fun x -> x) true;;
369 (But `(fun x -> x x)` still won't work.)
371 You may also see this:
373 # (function x -> x);;
376 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.
378 We can try our usual tricks:
380 # (fun x -> true) blackhole;;
383 OCaml declined to try to fully reduce the argument before applying the
384 lambda function. Question: Why is that? Didn't we say that OCaml is a call-by-value/eager language?
386 Remember that `blackhole` is a function too, so we can
387 reverse the order of the arguments:
389 # blackhole (fun x -> true);;
393 Now consider the following variations in behavior:
395 # let test = blackhole blackhole;;
396 <Infinite loop, need to control-c to interrupt>
398 # let test () = blackhole blackhole;;
399 val test : unit -> 'a = <fun>
402 - : unit -> 'a = <fun>
405 <Infinite loop, need to control-c to interrupt>
407 We can use functions that take arguments of type `unit` to control
408 execution. In Scheme parlance, functions on the `unit` type are called
409 *thunks* (which I've always assumed was a blend of "think" and "chunk").
411 Question: why do thunks work? We know that `blackhole ()` doesn't terminate, so why do expressions like:
413 let f = fun () -> blackhole ()
418 Bottom type, divergence
419 -----------------------
421 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:
423 type 'a option = None | Some of 'a;;
424 type 'a option = None | Some of 'a | bottom;;
426 Here are some exercises that may help better understand this. Figure out what is the type of each of the following:
434 let rec blackhole x = blackhole x in blackhole;;
436 let rec blackhole x = blackhole x in blackhole 1;;
438 let rec blackhole x = blackhole x in fun (y:int) -> blackhole y y y;;
440 let rec blackhole x = blackhole x in (blackhole 1) + 2;;
442 let rec blackhole x = blackhole x in (blackhole 1) || false;;
444 let rec blackhole x = blackhole x in 2 :: (blackhole 1);;
446 By the way, what's the type of this:
448 let rec blackhole (x:'a) : 'a = blackhole x in blackhole
451 Back to thunks: the reason you'd want to control evaluation with
452 thunks is to manipulate when "effects" happen. In a strongly
453 normalizing system, like the simply-typed lambda calculus or System F,
454 there are no "effects." In Scheme and OCaml, on the other hand, we can
455 write programs that have effects. One sort of effect is printing.
456 Another sort of effect is mutation, which we'll be looking at soon.
457 Continuations are yet another sort of effect. None of these are yet on
458 the table though. The only sort of effect we've got so far is
459 *divergence* or non-termination. So the only thing thunks are useful
460 for yet is controlling whether an expression that would diverge if we
461 tried to fully evaluate it does diverge. As we consider richer
462 languages, thunks will become more useful.