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