edits
[lambda.git] / topics / _week5_system_F.mdwn
1 [[!toc levels=2]]
2
3 # System F: the polymorphic lambda calculus
4
5 The simply-typed lambda calculus is beautifully simple, but it can't
6 even express the predecessor function, let alone full recursion.  And
7 we'll see shortly that there is good reason to be unsatisfied with the
8 simply-typed lambda calculus as a way of expressing natural language
9 meaning.  So we will need to get more sophisticated about types.  The
10 next step in that journey will be to consider System F.
11
12 In the simply-typed lambda calculus, we write types like <code>&sigma;
13 -> &tau;</code>.  This looks like logical implication.  We'll take
14 that resemblance seriously when we discuss the Curry-Howard
15 correspondence.  In the meantime, note that types respect modus
16 ponens: 
17
18 <pre>
19 Expression    Type      Implication
20 -----------------------------------
21 fn            &alpha; -> &beta;    &alpha; &sup; &beta;
22 arg           &alpha;         &alpha;
23 ------        ------    --------
24 (fn arg)      &beta;         &beta;
25 </pre>
26
27 The implication in the right-hand column is modus ponens, of course.
28
29 System F was discovered by Girard (the same guy who invented Linear
30 Logic), but it was independently proposed around the same time by
31 Reynolds, who called his version the *polymorphic lambda calculus*.
32 (Reynolds was also an early player in the development of
33 continuations.)  
34
35 System F enhances the simply-typed lambda calculus with abstraction
36 over types.  Normal lambda abstraction abstracts (binds) an expression
37 (a term); type abstraction abstracts (binds) a type.
38
39 In order to state System F, we'll need to adopt the
40 notational convention (which will last throughout the rest of the
41 course) that "<code>x:&alpha;</code>" represents an expression `x`
42 whose type is <code>&alpha;</code>.
43
44 Then System F can be specified as follows:
45
46         System F:
47         ---------
48         types       τ ::= c | α | τ1 -> τ2 | ∀α.τ
49         expressions e ::= x | λx:τ.e | e1 e2 | Λα.e | e [τ]
50
51 In the definition of the types, "`c`" is a type constant.  Type
52 constants play the role in System F that base types play in the
53 simply-typed lambda calculus.  So in a lingusitics context, type
54 constants might include `e` and `t`.  "α" is a type variable.  The
55 tick mark just indicates that the variable ranges over types rather
56 than over values; in various discussion below and later, type variables
57 can be distinguished by using letters from the greek alphabet
58 (&alpha;, &beta;, etc.), or by using capital roman letters (X, Y,
59 etc.).  "`τ1 -> τ2`" is the type of a function from expressions of
60 type `τ1` to expressions of type `τ2`.  And "`∀α.τ`" is called a
61 universal type, since it universally quantifies over the type variable
62 `'a`.  You can expect that in `∀α.τ`, the type `τ` will usually
63 have at least one free occurrence of `α` somewhere inside of it.
64
65 In the definition of the expressions, we have variables "`x`" as usual.
66 Abstracts "`λx:τ.e`" are similar to abstracts in the simply-typed lambda
67 calculus, except that they have their shrug variable annotated with a
68 type.  Applications "`e1 e2`" are just like in the simply-typed lambda calculus.
69
70 In addition to variables, abstracts, and applications, we have two
71 additional ways of forming expressions: "`Λα.e`" is called a *type
72 abstraction*, and "`e [τ]`" is called a *type application*.  The idea
73 is that <code>&Lambda;</code> is a capital <code>&lambda;</code>: just
74 like the lower-case <code>&lambda;</code>, <code>&Lambda;</code> binds
75 variables in its body, except that unlike <code>&lambda;</code>,
76 <code>&Lambda;</code> binds type variables instead of expression
77 variables.  So in the expression
78
79 <code>&Lambda; α (&lambda; x:α. x)</code>
80
81 the <code>&Lambda;</code> binds the type variable `α` that occurs in
82 the <code>&lambda;</code> abstract.  Of course, as long as type
83 variables are carefully distinguished from expression variables (by
84 tick marks, Grecification, or capitalization), there is no need to
85 distinguish expression abstraction from type abstraction by also
86 changing the shape of the lambda.
87
88 The expression immediately below is a polymorphic version of the
89 identity function.  It defines one general identity function that can
90 be adapted for use with expressions of any type. In order to get it
91 ready to apply this identity function to, say, a variable of type
92 boolean, just do this:
93
94 <code>(&Lambda; α (&lambda; x:α. x)) [t]</code>    
95
96 This type application (where `t` is a type constant for Boolean truth
97 values) specifies the value of the type variable `α`.  Not
98 surprisingly, the type of this type application is a function from
99 Booleans to Booleans:
100
101 <code>((&Lambda;α (&lambda; x:α . x)) [t]): (b->b)</code>    
102
103 Likewise, if we had instantiated the type variable as an entity (base
104 type `e`), the resulting identity function would have been a function
105 of type `e -> e`:
106
107 <code>((&Lambda;α (&lambda; x:α. x)) [e]): (e->e)</code>    
108
109 Clearly, for any choice of a type `α`, the identity function can be
110 instantiated as a function from expresions of type `α` to expressions
111 of type `α`.  In general, then, the type of the uninstantiated
112 (polymorphic) identity function is
113
114 <code>(&Lambda;α (&lambda;x:α . x)): (&forall;α. α-α)</code>
115
116 Pred in System F
117 ----------------
118
119 We saw that the predecessor function couldn't be expressed in the
120 simply-typed lambda calculus.  It *can* be expressed in System F,
121 however.  Here is one way, coded in
122 [[Benjamin Pierce's type-checker and evaluator for
123 System F|http://www.cis.upenn.edu/~bcpierce/tapl/index.html]] (the
124 relevant evaluator is called "fullpoly"):
125
126     N = ∀α.(α->α)->α->α;
127     Pair = (N->N->N)->N;
128
129     let zero = Λα. λs:α->α. λz:α. z in 
130     let fst = λx:N. λy:N. x in
131     let snd = λx:N. λy:N. y in
132     let pair = λx:N. λy:N. λz:N->N->N. z x y in
133     let suc = λn:N. Λα. λs:α->α. λz:α. s (n [α] s z) in
134     let shift = λp:Pair. pair (suc (p fst)) (p fst) in
135     let pre = λn:N. n [Pair] shift (pair zero zero) snd in
136
137     pre (suc (suc (suc zero)));
138
139 We've truncated the names of "suc(c)" and "pre(d)", since those are
140 reserved words in Pierce's system.  Note that in this code, there is
141 no typographic distinction between ordinary lambda and type-level
142 lambda, though the difference is encoded in whether the variables are
143 lower case (for ordinary lambda) or upper case (for type-level
144 lambda).
145
146 The key to the extra expressive power provided by System F is evident
147 in the typing imposed by the definition of `pre`.  The variable `n` is
148 typed as a Church number, i.e., as `∀α.(α->α)->α->α`.  The type
149 application `n [Pair]` instantiates `n` in a way that allows it to
150 manipulate ordered pairs: `n [Pair]: (Pair->Pair)->Pair->Pair`.  In
151 other words, the instantiation turns a Church number into a
152 pair-manipulating function, which is the heart of the strategy for
153 this version of predecessor.  
154
155 Could we try to build a system for doing Church arithmetic in which
156 the type for numbers always manipulated ordered pairs?  The problem is
157 that the ordered pairs we need here are pairs of numbers.  If we tried
158 to replace the type for Church numbers with a concrete (simple) type,
159 we would have to replace each `X` with the type for Pairs, `(N -> N ->
160 N) -> N`.  But then we'd have to replace each of these `N`'s with the
161 type for Church numbers, `(α -> α) -> α -> α`.  And then we'd have to
162 replace each of these `α`'s with... ad infinitum.  If we had to choose
163 a concrete type built entirely from explicit base types, we'd be
164 unable to proceed.
165  
166 [See Benjamin C. Pierce. 2002. *Types and Programming Languages*, MIT
167 Press, chapter 23.]
168
169 Typing &omega;
170 --------------
171
172 In fact, unlike in the simply-typed lambda calculus, 
173 it is even possible to give a type for &omega; in System F. 
174
175 <code>&omega; = λx:(∀α.α->α). x [∀α.α->α] x</code>
176
177 In order to see how this works, we'll apply &omega; to the identity
178 function.  
179
180 <code>&omega; id ==</code>
181
182     (λx:(∀α.α->α). x [∀α.α->α] x) (Λα.λx:α.x)
183
184 Since the type of the identity function is `∀α.α->α`, it's the
185 right type to serve as the argument to &omega;.  The definition of
186 &omega; instantiates the identity function by binding the type
187 variable `α` to the universal type `∀α.α->α`.  Instantiating the
188 identity function in this way results in an identity function whose
189 type is (in some sense, only accidentally) the same as the original
190 fully polymorphic identity function.
191
192 So in System F, unlike in the simply-typed lambda calculus, it *is*
193 possible for a function to apply to itself!
194
195 Does this mean that we can implement recursion in System F?  Not at
196 all.  In fact, despite its differences with the simply-typed lambda
197 calculus, one important property that System F shares with the
198 simply-typed lambda calculus is that they are both strongly
199 normalizing: *every* expression in either system reduces to a normal
200 form in a finite number of steps.  
201
202 Not only does a fixed-point combinator remain out of reach, we can't
203 even construct an infinite loop.  This means that although we found a
204 type for &omega;, there is no general type for &Omega; &equiv; &omega;
205 &omega;.  Furthermore, it turns out that no Turing complete system can
206 be strongly normalizing, from which it follows that System F is not
207 Turing complete.
208
209
210 ## Polymorphism in natural language
211
212 Is the simply-typed lambda calclus enough for analyzing natural
213 language, or do we need polymorphic types? Or something even more expressive?
214
215 The classic case study motivating polymorphism in natural language
216 comes from coordination.  (The locus classicus is Partee and Rooth
217 1983.)
218
219     Ann left and Bill left.
220     Ann left and slept.
221     Ann and Bill left.
222     Ann read and reviewed the book.
223
224 In English (likewise, many other languages), *and* can coordinate
225 clauses, verb phrases, determiner phrases, transitive verbs, and many
226 other phrase types.  In a garden-variety simply-typed grammar, each
227 kind of conjunct has a different semantic type, and so we would need
228 an independent rule for each one.  Yet there is a strong intuition
229 that the contribution of *and* remains constant across all of these
230 uses.  Can we capture this using polymorphic types?
231
232     Ann, Bill      e
233     left, slept    e -> t    
234     read, reviewed e -> e -> t
235
236 With these basic types, we want to say something like this:
237
238     and:t->t->t = λl:t. λr:t. l r false
239     and = Λα.Λβ.λl:α->β.λr:α->β.λx:α. and [β] (l x) (r x)
240
241 The idea is that the basic *and* conjoins expressions of type `t`, and
242 when *and* conjoins functional types, it builds a function that
243 distributes its argument across the two conjuncts and conjoins the two
244 results.  So `Ann left and slept` will evaluate to `(\x.and(left
245 x)(slept x)) ann`.  Following the terminology of Partee and Rooth, the
246 strategy of defining the coordination of expressions with complex
247 types in terms of the coordination of expressions with less complex
248 types is known as Generalized Coordination.
249
250 But the definitions just given are not well-formed expressions in
251 System F.  There are three problems.  The first is that we have two
252 definitions of the same word.  The intention is for one of the
253 definitions to be operative when the type of its arguments is type
254 `t`, but we have no way of conditioning evaluation on the *type* of an
255 argument.  The second is that for the polymorphic definition, the term
256 *and* occurs inside of the definition.  System F does not have
257 recursion.  
258
259 The third problem is more subtle.  The defintion as given takes two
260 types as parameters: the type of the first argument expected by each
261 conjunct, and the type of the result of applying each conjunct to an
262 argument of that type.  We would like to instantiate the recursive use
263 of *and* in the definition by using the result type.  But fully
264 instantiating the definition as given requires type application to a
265 pair of types, not to just a single type.  We want to somehow
266 guarantee that β will always itself be a complex type.
267
268 So conjunction and disjunction provide a compelling motivation for
269 polymorphism in natural language, but we don't yet have the ability to
270 build the polymorphism into a formal system.
271
272 And in fact, discussions of generalized coordination in the
273 linguistics literature are almost always left as a meta-level
274 generalizations over a basic simply-typed grammar.  For instance, in
275 Hendriks' 1992:74 dissertation, generalized coordination is
276 implemented as a method for generating a suitable set of translation
277 rules, which are in turn expressed in a simply-typed grammar.
278
279 Not incidentally, we're not aware of any programming language that
280 makes generalized coordination available, despite is naturalness and
281 ubiquity in natural language.  That is, coordination in programming
282 languages is always at the sentential level.  You might be able to
283 evaluate `(delete file1) and (delete file2)`, but never `delete (file1
284 and file2)`.
285
286 We'll return to thinking about generalized coordination as we get
287 deeper into types.  There will be an analysis in term of continuations
288 that will be particularly satisfying.
289
290
291 #Types in OCaml
292
293
294 OCaml has type inference: the system can often infer what the type of
295 an expression must be, based on the type of other known expressions.
296
297 For instance, if we type
298
299     # let f x = x + 3;;
300
301 The system replies with
302
303     val f : int -> int = <fun>
304
305 Since `+` is only defined on integers, it has type
306
307      # (+);;
308      - : int -> int -> int = <fun>
309
310 The parentheses are there to turn off the trick that allows the two
311 arguments of `+` to surround it in infix (for linguists, SOV) argument
312 order. That is,
313
314     # 3 + 4 = (+) 3 4;;
315     - : bool = true
316
317 In general, tuples with one element are identical to their one
318 element:
319
320     # (3) = 3;;
321     - : bool = true
322
323 though OCaml, like many systems, refuses to try to prove whether two
324 functional objects may be identical:
325
326     # (f) = f;;
327     Exception: Invalid_argument "equal: functional value".
328
329 Oh well.
330
331 [Note: There is a limited way you can compare functions, using the
332 `==` operator instead of the `=` operator. Later when we discuss mutation,
333 we'll discuss the difference between these two equality operations.
334 Scheme has a similar pair, which they name `eq?` and `equal?`. In Python,
335 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
336 `(f) = f`. However, don't expect it to figure out in general when two functions
337 are equivalent. (That question is not Turing computable.)
338
339         # (f) == (fun x -> x + 3);;
340         - : bool = false
341
342 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.]
343
344
345
346 Booleans in OCaml, and simple pattern matching
347 ----------------------------------------------
348
349 Where we would write `true 1 2` in our pure lambda calculus and expect
350 it to evaluate to `1`, in OCaml boolean types are not functions
351 (equivalently, they're functions that take zero arguments). Instead, selection is
352 accomplished as follows:
353
354     # if true then 1 else 2;;
355     - : int = 1
356
357 The types of the `then` clause and of the `else` clause must be the
358 same.
359
360 The `if` construction can be re-expressed by means of the following
361 pattern-matching expression:
362
363     match <bool expression> with true -> <expression1> | false -> <expression2>
364
365 That is,
366
367     # match true with true -> 1 | false -> 2;;
368     - : int = 1
369
370 Compare with
371
372     # match 3 with 1 -> 1 | 2 -> 4 | 3 -> 9;;
373     - : int = 9
374
375 Unit and thunks
376 ---------------
377
378 All functions in OCaml take exactly one argument.  Even this one:
379
380     # let f x y = x + y;;
381     # f 2 3;;
382     - : int = 5
383
384 Here's how to tell that `f` has been curry'd:
385
386     # f 2;;
387     - : int -> int = <fun>
388
389 After we've given our `f` one argument, it returns a function that is
390 still waiting for another argument.
391
392 There is a special type in OCaml called `unit`.  There is exactly one
393 object in this type, written `()`.  So
394
395     # ();;
396     - : unit = ()
397
398 Just as you can define functions that take constants for arguments
399
400     # let f 2 = 3;;
401     # f 2;;
402     - : int = 3;;
403
404 you can also define functions that take the unit as its argument, thus
405
406     # let f () = 3;;
407     val f : unit -> int = <fun>
408
409 Then the only argument you can possibly apply `f` to that is of the
410 correct type is the unit:
411
412     # f ();;
413     - : int = 3
414
415 Now why would that be useful?
416
417 Let's have some fun: think of `rec` as our `Y` combinator.  Then
418
419     # let rec f n = if (0 = n) then 1 else (n * (f (n - 1)));;
420     val f : int -> int = <fun>
421     # f 5;;
422     - : int = 120
423
424 We can't define a function that is exactly analogous to our &omega;.
425 We could try `let rec omega x = x x;;` what happens?
426
427 [Note: if you want to learn more OCaml, you might come back here someday and try:
428
429         # let id x = x;;
430         val id : 'a -> 'a = <fun>
431         # let unwrap (`Wrap a) = a;;
432         val unwrap : [< `Wrap of 'a ] -> 'a = <fun>
433         # let omega ((`Wrap x) as y) = x y;;
434         val omega : [< `Wrap of [> `Wrap of 'a ] -> 'b as 'a ] -> 'b = <fun>
435         # unwrap (omega (`Wrap id)) == id;;
436         - : bool = true
437         # unwrap (omega (`Wrap omega));;
438     <Infinite loop, need to control-c to interrupt>
439
440 But we won't try to explain this now.]
441
442
443 Even if we can't (easily) express omega in OCaml, we can do this:
444
445     # let rec blackhole x = blackhole x;;
446
447 By the way, what's the type of this function?
448
449 If you then apply this `blackhole` function to an argument,
450
451     # blackhole 3;;
452
453 the interpreter goes into an infinite loop, and you have to type control-c
454 to break the loop.
455
456 Oh, one more thing: lambda expressions look like this:
457
458     # (fun x -> x);;
459     - : 'a -> 'a = <fun>
460     # (fun x -> x) true;;
461     - : bool = true
462
463 (But `(fun x -> x x)` still won't work.)
464
465 You may also see this:
466
467         # (function x -> x);;
468         - : 'a -> 'a = <fun>
469
470 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.
471
472 We can try our usual tricks:
473
474     # (fun x -> true) blackhole;;
475     - : bool = true
476
477 OCaml declined to try to fully reduce the argument before applying the
478 lambda function. Question: Why is that? Didn't we say that OCaml is a call-by-value/eager language?
479
480 Remember that `blackhole` is a function too, so we can
481 reverse the order of the arguments:
482
483     # blackhole (fun x -> true);;
484
485 Infinite loop.
486
487 Now consider the following variations in behavior:
488
489     # let test = blackhole blackhole;;
490     <Infinite loop, need to control-c to interrupt>
491
492     # let test () = blackhole blackhole;;
493     val test : unit -> 'a = <fun>
494
495     # test;;
496     - : unit -> 'a = <fun>
497
498     # test ();;
499     <Infinite loop, need to control-c to interrupt>
500
501 We can use functions that take arguments of type `unit` to control
502 execution.  In Scheme parlance, functions on the `unit` type are called
503 *thunks* (which I've always assumed was a blend of "think" and "chunk").
504
505 Question: why do thunks work? We know that `blackhole ()` doesn't terminate, so why do expressions like:
506
507         let f = fun () -> blackhole ()
508         in true
509
510 terminate?
511
512 Bottom type, divergence
513 -----------------------
514
515 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:
516
517         type 'a option = None | Some of 'a;;
518         type 'a option = None | Some of 'a | bottom;;
519
520 Here are some exercises that may help better understand this. Figure out what is the type of each of the following:
521
522         fun x y -> y;;
523
524         fun x (y:int) -> y;;
525
526         fun x y : int -> y;;
527
528         let rec blackhole x = blackhole x in blackhole;;
529
530         let rec blackhole x = blackhole x in blackhole 1;;
531
532         let rec blackhole x = blackhole x in fun (y:int) -> blackhole y y y;;
533
534         let rec blackhole x = blackhole x in (blackhole 1) + 2;;
535
536         let rec blackhole x = blackhole x in (blackhole 1) || false;;
537
538         let rec blackhole x = blackhole x in 2 :: (blackhole 1);;
539
540 By the way, what's the type of this:
541
542         let rec blackhole (x:'a) : 'a = blackhole x in blackhole
543
544
545 Back to thunks: the reason you'd want to control evaluation with
546 thunks is to manipulate when "effects" happen. In a strongly
547 normalizing system, like the simply-typed lambda calculus or System F,
548 there are no "effects." In Scheme and OCaml, on the other hand, we can
549 write programs that have effects. One sort of effect is printing.
550 Another sort of effect is mutation, which we'll be looking at soon.
551 Continuations are yet another sort of effect. None of these are yet on
552 the table though. The only sort of effect we've got so far is
553 *divergence* or non-termination. So the only thing thunks are useful
554 for yet is controlling whether an expression that would diverge if we
555 tried to fully evaluate it does diverge. As we consider richer
556 languages, thunks will become more useful.