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