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