edits
[lambda.git] / topics / _week5_system_F.mdwn
1 # System F and recursive types
2
3 In the simply-typed lambda calculus, we write types like <code>&sigma;
4 -> &tau;</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
7 ponens: 
8
9 <pre>
10 Expression    Type      Implication
11 -----------------------------------
12 fn            &alpha; -> &beta;    &alpha; &sup; &beta;
13 arg           &alpha;         &alpha;
14 ------        ------    --------
15 (fn arg)      &beta;         &beta;
16 </pre>
17
18 The implication in the right-hand column is modus ponens, of course.
19
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
24 continuations.)  
25
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.
29
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:&alpha;</code>" represents an expression `x`
33 whose type is <code>&alpha;</code>.
34
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):
37
38         System F:
39         ---------
40         types τ ::= c | 'a | τ1 -> τ2 | ∀'a. τ
41         expressions e ::= x | λx:τ. e | e1 e2 | Λ'a. e | e [τ]
42
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 (&alpha;, &beta;, 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.
56
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.
61
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>&Lambda;</code> is a capital <code>&lambda;</code>: just
66 like the lower-case <code>&lambda;</code>, <code>&Lambda;</code> binds
67 variables in its body, except that unlike <code>&lambda;</code>,
68 <code>&Lambda;</code> binds type variables instead of expression
69 variables.  So in the expression
70
71 <code>&Lambda; 'a (&lambda; x:'a . x)</code>
72
73 the <code>&Lambda;</code> binds the type variable `'a` that occurs in
74 the <code>&lambda;</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.
79
80 The expression immediately below is a polymorphic version of the
81 identity function.  It defines one general identity function that can
82 be adapted for use with expressions of any type. In order to get it
83 ready to apply this identity function to, say, a variable of type
84 boolean, just do this:
85
86 <code>(&Lambda; 'a (&lambda; x:'a . x)) [t]</code>    
87
88 This type application (where `t` is a type constant for Boolean truth
89 values) specifies the value of the type variable `'a`.  Not
90 surprisingly, the type of this type application is a function from
91 Booleans to Booleans:
92
93 <code>((&Lambda; 'a (&lambda; x:'a . x)) [t]): (b -> b)</code>    
94
95 Likewise, if we had instantiated the type variable as an entity (base
96 type `e`), the resulting identity function would have been a function
97 of type `e -> e`:
98
99 <code>((&Lambda; 'a (&lambda; x:'a . x)) [e]): (e -> e)</code>    
100
101 Clearly, for any choice of a type `'a`, the identity function can be
102 instantiated as a function from expresions of type `'a` to expressions
103 of type `'a`.  In general, then, the type of the uninstantiated
104 (polymorphic) identity function is
105
106 <code>(&Lambda; 'a (&lambda; x:'a . x)): (&forall; 'a . 'a -> 'a)</code>
107
108 Pred in System F
109 ----------------
110
111 We saw that the predecessor function couldn't be expressed in the
112 simply-typed lambda calculus.  It *can* be expressed in System F,
113 however.  Here is one way, coded in
114 [[Benjamin Pierce's type-checker and evaluator for
115 System F|http://www.cis.upenn.edu/~bcpierce/tapl/index.html]] (the
116 relevant evaluator is called "fullpoly"):
117
118     N = All X . (X->X)->X->X;
119     Pair = (N -> N -> N) -> N;
120     let zero = lambda X . lambda s:X->X . lambda z:X. z in 
121     let fst = lambda x:N . lambda y:N . x in
122     let snd = lambda x:N . lambda y:N . y in
123     let pair = lambda x:N . lambda y:N . lambda z:N->N->N . z x y in
124     let suc = lambda n:N . lambda X . lambda s:X->X . lambda z:X . s (n [X] s z) in
125     let shift = lambda p:Pair . pair (suc (p fst)) (p fst) in
126     let pre = lambda n:N . n [Pair] shift (pair zero zero) snd in
127
128     pre (suc (suc (suc zero)));
129
130 We've truncated the names of "suc(c)" and "pre(d)", since those are
131 reserved words in Pierce's system.  Note that in this code, there is
132 no typographic distinction between ordinary lambda and type-level
133 lambda, though the difference is encoded in whether the variables are
134 lower case (for ordinary lambda) or upper case (for type-level
135 lambda).
136
137 The key to the extra expressive power provided by System F is evident
138 in the typing imposed by the definition of `pre`.  The variable `n` is
139 typed as a Church number, i.e., as `All X . (X->X)->X->X`.  The type
140 application `n [Pair]` instantiates `n` in a way that allows it to
141 manipulate ordered pairs: `n [Pair]: (Pair->Pair)->Pair->Pair`.  In
142 other words, the instantiation turns a Church number into a
143 pair-manipulating function, which is the heart of the strategy for
144 this version of predecessor.  
145
146 Could we try to build a system for doing Church arithmetic in which
147 the type for numbers always manipulated ordered pairs?  The problem is
148 that the ordered pairs we need here are pairs of numbers.  If we tried
149 to replace the type for Church numbers with a concrete (simple) type,
150 we would have to replace each `X` with the type for Pairs, `(N -> N ->
151 N) -> N`.  But then we'd have to replace each of these `N`'s with the
152 type for Church numbers, `(X -> X) -> X -> X`.  And then we'd have to
153 replace each of these `X`'s with... ad infinitum.  If we had to choose
154 a concrete type built entirely from explicit base types, we'd be
155 unable to proceed.
156  
157 [See Benjamin C. Pierce. 2002. *Types and Programming Languages*, MIT
158 Press, chapter 23.]
159
160 Typing &omega;
161 --------------
162
163 In fact, unlike in the simply-typed lambda calculus, 
164 it is even possible to give a type for &omega; in System F. 
165
166 <code>&omega; = lambda x:(All X. X->X) . x [All X . X->X] x</code>
167
168 In order to see how this works, we'll apply &omega; to the identity
169 function.  
170
171 <code>&omega; id ==</code>
172
173     (lambda x:(All X . X->X) . x [All X . X->X] x) (lambda X . lambda x:X . x)
174
175 Since the type of the identity function is `(All X . X->X)`, it's the
176 right type to serve as the argument to &omega;.  The definition of
177 &omega; instantiates the identity function by binding the type
178 variable `X` to the universal type `All X . X->X`.  Instantiating the
179 identity function in this way results in an identity function whose
180 type is (in some sense, only accidentally) the same as the original
181 fully polymorphic identity function.
182
183 So in System F, unlike in the simply-typed lambda calculus, it *is*
184 possible for a function to apply to itself!
185
186 Does this mean that we can implement recursion in System F?  Not at
187 all.  In fact, despite its differences with the simply-typed lambda
188 calculus, one important property that System F shares with the
189 simply-typed lambda calculus is that they are both strongly
190 normalizing: *every* expression in either system reduces to a normal
191 form in a finite number of steps.  
192
193 Not only does a fixed-point combinator remain out of reach, we can't
194 even construct an infinite loop.  This means that although we found a
195 type for &omega;, there is no general type for &Omega; &equiv; &omega;
196 &omega;.  Furthermore, it turns out that no Turing complete system can
197 be strongly normalizing, from which it follows that System F is not
198 Turing complete.
199
200
201 Types in OCaml
202 --------------
203
204 OCaml has type inference: the system can often infer what the type of
205 an expression must be, based on the type of other known expressions.
206
207 For instance, if we type
208
209     # let f x = x + 3;;
210
211 The system replies with
212
213     val f : int -> int = <fun>
214
215 Since `+` is only defined on integers, it has type
216
217      # (+);;
218      - : int -> int -> int = <fun>
219
220 The parentheses are there to turn off the trick that allows the two
221 arguments of `+` to surround it in infix (for linguists, SOV) argument
222 order. That is,
223
224     # 3 + 4 = (+) 3 4;;
225     - : bool = true
226
227 In general, tuples with one element are identical to their one
228 element:
229
230     # (3) = 3;;
231     - : bool = true
232
233 though OCaml, like many systems, refuses to try to prove whether two
234 functional objects may be identical:
235
236     # (f) = f;;
237     Exception: Invalid_argument "equal: functional value".
238
239 Oh well.
240
241 [Note: There is a limited way you can compare functions, using the
242 `==` operator instead of the `=` operator. Later when we discuss mutation,
243 we'll discuss the difference between these two equality operations.
244 Scheme has a similar pair, which they name `eq?` and `equal?`. In Python,
245 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
246 `(f) = f`. However, don't expect it to figure out in general when two functions
247 are equivalent. (That question is not Turing computable.)
248
249         # (f) == (fun x -> x + 3);;
250         - : bool = false
251
252 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.]
253
254
255
256 Booleans in OCaml, and simple pattern matching
257 ----------------------------------------------
258
259 Where we would write `true 1 2` in our pure lambda calculus and expect
260 it to evaluate to `1`, in OCaml boolean types are not functions
261 (equivalently, they're functions that take zero arguments). Instead, selection is
262 accomplished as follows:
263
264     # if true then 1 else 2;;
265     - : int = 1
266
267 The types of the `then` clause and of the `else` clause must be the
268 same.
269
270 The `if` construction can be re-expressed by means of the following
271 pattern-matching expression:
272
273     match <bool expression> with true -> <expression1> | false -> <expression2>
274
275 That is,
276
277     # match true with true -> 1 | false -> 2;;
278     - : int = 1
279
280 Compare with
281
282     # match 3 with 1 -> 1 | 2 -> 4 | 3 -> 9;;
283     - : int = 9
284
285 Unit and thunks
286 ---------------
287
288 All functions in OCaml take exactly one argument.  Even this one:
289
290     # let f x y = x + y;;
291     # f 2 3;;
292     - : int = 5
293
294 Here's how to tell that `f` has been curry'd:
295
296     # f 2;;
297     - : int -> int = <fun>
298
299 After we've given our `f` one argument, it returns a function that is
300 still waiting for another argument.
301
302 There is a special type in OCaml called `unit`.  There is exactly one
303 object in this type, written `()`.  So
304
305     # ();;
306     - : unit = ()
307
308 Just as you can define functions that take constants for arguments
309
310     # let f 2 = 3;;
311     # f 2;;
312     - : int = 3;;
313
314 you can also define functions that take the unit as its argument, thus
315
316     # let f () = 3;;
317     val f : unit -> int = <fun>
318
319 Then the only argument you can possibly apply `f` to that is of the
320 correct type is the unit:
321
322     # f ();;
323     - : int = 3
324
325 Now why would that be useful?
326
327 Let's have some fun: think of `rec` as our `Y` combinator.  Then
328
329     # let rec f n = if (0 = n) then 1 else (n * (f (n - 1)));;
330     val f : int -> int = <fun>
331     # f 5;;
332     - : int = 120
333
334 We can't define a function that is exactly analogous to our &omega;.
335 We could try `let rec omega x = x x;;` what happens?
336
337 [Note: if you want to learn more OCaml, you might come back here someday and try:
338
339         # let id x = x;;
340         val id : 'a -> 'a = <fun>
341         # let unwrap (`Wrap a) = a;;
342         val unwrap : [< `Wrap of 'a ] -> 'a = <fun>
343         # let omega ((`Wrap x) as y) = x y;;
344         val omega : [< `Wrap of [> `Wrap of 'a ] -> 'b as 'a ] -> 'b = <fun>
345         # unwrap (omega (`Wrap id)) == id;;
346         - : bool = true
347         # unwrap (omega (`Wrap omega));;
348     <Infinite loop, need to control-c to interrupt>
349
350 But we won't try to explain this now.]
351
352
353 Even if we can't (easily) express omega in OCaml, we can do this:
354
355     # let rec blackhole x = blackhole x;;
356
357 By the way, what's the type of this function?
358
359 If you then apply this `blackhole` function to an argument,
360
361     # blackhole 3;;
362
363 the interpreter goes into an infinite loop, and you have to type control-c
364 to break the loop.
365
366 Oh, one more thing: lambda expressions look like this:
367
368     # (fun x -> x);;
369     - : 'a -> 'a = <fun>
370     # (fun x -> x) true;;
371     - : bool = true
372
373 (But `(fun x -> x x)` still won't work.)
374
375 You may also see this:
376
377         # (function x -> x);;
378         - : 'a -> 'a = <fun>
379
380 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.
381
382 We can try our usual tricks:
383
384     # (fun x -> true) blackhole;;
385     - : bool = true
386
387 OCaml declined to try to fully reduce the argument before applying the
388 lambda function. Question: Why is that? Didn't we say that OCaml is a call-by-value/eager language?
389
390 Remember that `blackhole` is a function too, so we can
391 reverse the order of the arguments:
392
393     # blackhole (fun x -> true);;
394
395 Infinite loop.
396
397 Now consider the following variations in behavior:
398
399     # let test = blackhole blackhole;;
400     <Infinite loop, need to control-c to interrupt>
401
402     # let test () = blackhole blackhole;;
403     val test : unit -> 'a = <fun>
404
405     # test;;
406     - : unit -> 'a = <fun>
407
408     # test ();;
409     <Infinite loop, need to control-c to interrupt>
410
411 We can use functions that take arguments of type `unit` to control
412 execution.  In Scheme parlance, functions on the `unit` type are called
413 *thunks* (which I've always assumed was a blend of "think" and "chunk").
414
415 Question: why do thunks work? We know that `blackhole ()` doesn't terminate, so why do expressions like:
416
417         let f = fun () -> blackhole ()
418         in true
419
420 terminate?
421
422 Bottom type, divergence
423 -----------------------
424
425 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:
426
427         type 'a option = None | Some of 'a;;
428         type 'a option = None | Some of 'a | bottom;;
429
430 Here are some exercises that may help better understand this. Figure out what is the type of each of the following:
431
432         fun x y -> y;;
433
434         fun x (y:int) -> y;;
435
436         fun x y : int -> y;;
437
438         let rec blackhole x = blackhole x in blackhole;;
439
440         let rec blackhole x = blackhole x in blackhole 1;;
441
442         let rec blackhole x = blackhole x in fun (y:int) -> blackhole y y y;;
443
444         let rec blackhole x = blackhole x in (blackhole 1) + 2;;
445
446         let rec blackhole x = blackhole x in (blackhole 1) || false;;
447
448         let rec blackhole x = blackhole x in 2 :: (blackhole 1);;
449
450 By the way, what's the type of this:
451
452         let rec blackhole (x:'a) : 'a = blackhole x in blackhole
453
454
455 Back to thunks: the reason you'd want to control evaluation with
456 thunks is to manipulate when "effects" happen. In a strongly
457 normalizing system, like the simply-typed lambda calculus or System F,
458 there are no "effects." In Scheme and OCaml, on the other hand, we can
459 write programs that have effects. One sort of effect is printing.
460 Another sort of effect is mutation, which we'll be looking at soon.
461 Continuations are yet another sort of effect. None of these are yet on
462 the table though. The only sort of effect we've got so far is
463 *divergence* or non-termination. So the only thing thunks are useful
464 for yet is controlling whether an expression that would diverge if we
465 tried to fully evaluate it does diverge. As we consider richer
466 languages, thunks will become more useful.