3 # System F: the polymorphic lambda calculus
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.
12 In the simply-typed lambda calculus, we write types like <code>σ
13 -> τ</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
19 Expression Type Implication
20 -----------------------------------
21 fn α -> β α ⊃ β
23 ------ ------ --------
24 (fn arg) β β
27 The implication in the right-hand column is modus ponens, of course.
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
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.
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:α</code>" represents an expression `x`
42 whose type is <code>α</code>.
44 Then System F can be specified as follows:
48 types τ ::= c | α | τ1 -> τ2 | ∀α.τ
49 expressions e ::= x | λx:τ.e | e1 e2 | Λα.e | e [τ]
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. In
55 various discussions, type variables are distinguished by using letters
56 from the greek alphabet (α, β, etc.), as we do here, or by
57 using capital roman letters (X, Y, etc.), or by adding a tick mark
58 (`'a`, `'b`, etc.), as in OCaml. "`τ1 -> τ2`" is the type of a
59 function from expressions of type `τ1` to expressions of type `τ2`.
60 And "`∀α.τ`" is called a universal type, since it universally
61 quantifies over the type variable `α`. You can expect that in
62 `∀α.τ`, the type `τ` will usually have at least one free occurrence of
63 `α` somewhere inside of it.
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.
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>Λ</code> is a capital <code>λ</code>: just
74 like the lower-case <code>λ</code>, <code>Λ</code> binds
75 variables in its body, except that unlike <code>λ</code>,
76 <code>Λ</code> binds type variables instead of expression
77 variables. So in the expression
79 <code>Λ α (λ x:α. x)</code>
81 the <code>Λ</code> binds the type variable `α` that occurs in
82 the <code>λ</code> abstract.
84 This expression is a polymorphic version of the identity function. It
85 defines one general identity function that can be adapted for use with
86 expressions of any type. In order to get it ready to apply this
87 identity function to, say, a variable of type boolean, just do this:
89 <code>(Λ α (λ x:α. x)) [t]</code>
91 This type application (where `t` is a type constant for Boolean truth
92 values) specifies the value of the type variable `α`. Not
93 surprisingly, the type of the expression that results from this type
94 application is a function from Booleans to Booleans:
96 <code>((Λα (λ x:α . x)) [t]): (b->b)</code>
98 Likewise, if we had instantiated the type variable as an entity (base
99 type `e`), the resulting identity function would have been a function
102 <code>((Λα (λ x:α. x)) [e]): (e->e)</code>
104 Clearly, for any choice of a type `α`, the identity function can be
105 instantiated as a function from expresions of type `α` to expressions
106 of type `α`. In general, then, the type of the uninstantiated
107 (polymorphic) identity function is
109 <code>(Λα (λx:α . x)): (∀α. α->α)</code>
114 We saw that the predecessor function couldn't be expressed in the
115 simply-typed lambda calculus. It *can* be expressed in System F,
116 however. Here is one way:
118 let N = ∀α.(α->α)->α->α in
119 let Pair = (N->N->N)->N in
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. Λα. λ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
129 pre (suc (suc (suc zero)));
131 [If you want to run this code in
132 [[Benjamin Pierce's type-checker and evaluator for
133 System F|http://www.cis.upenn.edu/~bcpierce/tapl/index.html]], the
134 relevant evaluator is called "fullpoly", and you'll need to
135 truncate the names of "suc(c)" and "pre(d)", since those are
136 reserved words in Pierce's system.]
138 Exercise: convince yourself that `zero` has type `N`.
140 The key to the extra expressive power provided by System F is evident
141 in the typing imposed by the definition of `pre`. The variable `n` is
142 typed as a Church number, i.e., as `∀α.(α->α)->α->α`. The type
143 application `n [Pair]` instantiates `n` in a way that allows it to
144 manipulate ordered pairs: `n [Pair]: (Pair->Pair)->Pair->Pair`. In
145 other words, the instantiation turns a Church number into a
146 pair-manipulating function, which is the heart of the strategy for
147 this version of predecessor.
149 Could we try to build a system for doing Church arithmetic in which
150 the type for numbers always manipulated ordered pairs? The problem is
151 that the ordered pairs we need here are pairs of numbers. If we tried
152 to replace the type for Church numbers with a concrete (simple) type,
153 we would have to replace each `X` with the type for Pairs, `(N -> N ->
154 N) -> N`. But then we'd have to replace each of these `N`'s with the
155 type for Church numbers, `(α -> α) -> α -> α`. And then we'd have to
156 replace each of these `α`'s with... ad infinitum. If we had to choose
157 a concrete type built entirely from explicit base types, we'd be
160 [See Benjamin C. Pierce. 2002. *Types and Programming Languages*, MIT
166 In fact, unlike in the simply-typed lambda calculus,
167 it is even possible to give a type for ω in System F.
169 <code>ω = λx:(∀α.α->α). x [∀α.α->α] x</code>
171 In order to see how this works, we'll apply ω to the identity
174 <code>ω id ==</code>
176 (λx:(∀α.α->α). x [∀α.α->α] x) (Λα.λx:α.x)
178 Since the type of the identity function is `∀α.α->α`, it's the
179 right type to serve as the argument to ω. The definition of
180 ω instantiates the identity function by binding the type
181 variable `α` to the universal type `∀α.α->α`. Instantiating the
182 identity function in this way results in an identity function whose
183 type is (in some sense, only accidentally) the same as the original
184 fully polymorphic identity function.
186 So in System F, unlike in the simply-typed lambda calculus, it *is*
187 possible for a function to apply to itself!
189 Does this mean that we can implement recursion in System F? Not at
190 all. In fact, despite its differences with the simply-typed lambda
191 calculus, one important property that System F shares with the
192 simply-typed lambda calculus is that they are both strongly
193 normalizing: *every* expression in either system reduces to a normal
194 form in a finite number of steps.
196 Not only does a fixed-point combinator remain out of reach, we can't
197 even construct an infinite loop. This means that although we found a
198 type for ω, there is no general type for Ω ≡ ω
199 ω. Furthermore, it turns out that no Turing complete system can
200 be strongly normalizing, from which it follows that System F is not
204 ## Polymorphism in natural language
206 Is the simply-typed lambda calclus enough for analyzing natural
207 language, or do we need polymorphic types? Or something even more expressive?
209 The classic case study motivating polymorphism in natural language
210 comes from coordination. (The locus classicus is Partee and Rooth
213 Ann left and Bill left.
216 Ann read and reviewed the book.
218 In English (likewise, many other languages), *and* can coordinate
219 clauses, verb phrases, determiner phrases, transitive verbs, and many
220 other phrase types. In a garden-variety simply-typed grammar, each
221 kind of conjunct has a different semantic type, and so we would need
222 an independent rule for each one. Yet there is a strong intuition
223 that the contribution of *and* remains constant across all of these
224 uses. Can we capture this using polymorphic types?
228 read, reviewed e -> e -> t
230 With these basic types, we want to say something like this:
232 and:t->t->t = λl:t. λr:t. l r false
233 and = Λα.Λβ.λl:α->β.λr:α->β.λx:α. and [β] (l x) (r x)
235 The idea is that the basic *and* conjoins expressions of type `t`, and
236 when *and* conjoins functional types, it builds a function that
237 distributes its argument across the two conjuncts and conjoins the two
238 results. So `Ann left and slept` will evaluate to `(\x.and(left
239 x)(slept x)) ann`. Following the terminology of Partee and Rooth, the
240 strategy of defining the coordination of expressions with complex
241 types in terms of the coordination of expressions with less complex
242 types is known as Generalized Coordination.
244 But the definitions just given are not well-formed expressions in
245 System F. There are three problems. The first is that we have two
246 definitions of the same word. The intention is for one of the
247 definitions to be operative when the type of its arguments is type
248 `t`, but we have no way of conditioning evaluation on the *type* of an
249 argument. The second is that for the polymorphic definition, the term
250 *and* occurs inside of the definition. System F does not have
253 The third problem is more subtle. The defintion as given takes two
254 types as parameters: the type of the first argument expected by each
255 conjunct, and the type of the result of applying each conjunct to an
256 argument of that type. We would like to instantiate the recursive use
257 of *and* in the definition by using the result type. But fully
258 instantiating the definition as given requires type application to a
259 pair of types, not to just a single type. We want to somehow
260 guarantee that β will always itself be a complex type.
262 So conjunction and disjunction provide a compelling motivation for
263 polymorphism in natural language, but we don't yet have the ability to
264 build the polymorphism into a formal system.
266 And in fact, discussions of generalized coordination in the
267 linguistics literature are almost always left as a meta-level
268 generalizations over a basic simply-typed grammar. For instance, in
269 Hendriks' 1992:74 dissertation, generalized coordination is
270 implemented as a method for generating a suitable set of translation
271 rules, which are in turn expressed in a simply-typed grammar.
273 Not incidentally, we're not aware of any programming language that
274 makes generalized coordination available, despite is naturalness and
275 ubiquity in natural language. That is, coordination in programming
276 languages is always at the sentential level. You might be able to
277 evaluate `(delete file1) and (delete file2)`, but never `delete (file1
280 We'll return to thinking about generalized coordination as we get
281 deeper into types. There will be an analysis in term of continuations
282 that will be particularly satisfying.
288 OCaml has type inference: the system can often infer what the type of
289 an expression must be, based on the type of other known expressions.
291 For instance, if we type
295 The system replies with
297 val f : int -> int = <fun>
299 Since `+` is only defined on integers, it has type
302 - : int -> int -> int = <fun>
304 The parentheses are there to turn off the trick that allows the two
305 arguments of `+` to surround it in infix (for linguists, SOV) argument
311 In general, tuples with one element are identical to their one
317 though OCaml, like many systems, refuses to try to prove whether two
318 functional objects may be identical:
321 Exception: Invalid_argument "equal: functional value".
325 [Note: There is a limited way you can compare functions, using the
326 `==` operator instead of the `=` operator. Later when we discuss mutation,
327 we'll discuss the difference between these two equality operations.
328 Scheme has a similar pair, which they name `eq?` and `equal?`. In Python,
329 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
330 `(f) = f`. However, don't expect it to figure out in general when two functions
331 are equivalent. (That question is not Turing computable.)
333 # (f) == (fun x -> x + 3);;
336 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.]
340 Booleans in OCaml, and simple pattern matching
341 ----------------------------------------------
343 Where we would write `true 1 2` in our pure lambda calculus and expect
344 it to evaluate to `1`, in OCaml boolean types are not functions
345 (equivalently, they're functions that take zero arguments). Instead, selection is
346 accomplished as follows:
348 # if true then 1 else 2;;
351 The types of the `then` clause and of the `else` clause must be the
354 The `if` construction can be re-expressed by means of the following
355 pattern-matching expression:
357 match <bool expression> with true -> <expression1> | false -> <expression2>
361 # match true with true -> 1 | false -> 2;;
366 # match 3 with 1 -> 1 | 2 -> 4 | 3 -> 9;;
372 All functions in OCaml take exactly one argument. Even this one:
374 # let f x y = x + y;;
378 Here's how to tell that `f` has been curry'd:
381 - : int -> int = <fun>
383 After we've given our `f` one argument, it returns a function that is
384 still waiting for another argument.
386 There is a special type in OCaml called `unit`. There is exactly one
387 object in this type, written `()`. So
392 Just as you can define functions that take constants for arguments
398 you can also define functions that take the unit as its argument, thus
401 val f : unit -> int = <fun>
403 Then the only argument you can possibly apply `f` to that is of the
404 correct type is the unit:
409 Now why would that be useful?
411 Let's have some fun: think of `rec` as our `Y` combinator. Then
413 # let rec f n = if (0 = n) then 1 else (n * (f (n - 1)));;
414 val f : int -> int = <fun>
418 We can't define a function that is exactly analogous to our ω.
419 We could try `let rec omega x = x x;;` what happens?
421 [Note: if you want to learn more OCaml, you might come back here someday and try:
424 val id : 'a -> 'a = <fun>
425 # let unwrap (`Wrap a) = a;;
426 val unwrap : [< `Wrap of 'a ] -> 'a = <fun>
427 # let omega ((`Wrap x) as y) = x y;;
428 val omega : [< `Wrap of [> `Wrap of 'a ] -> 'b as 'a ] -> 'b = <fun>
429 # unwrap (omega (`Wrap id)) == id;;
431 # unwrap (omega (`Wrap omega));;
432 <Infinite loop, need to control-c to interrupt>
434 But we won't try to explain this now.]
437 Even if we can't (easily) express omega in OCaml, we can do this:
439 # let rec blackhole x = blackhole x;;
441 By the way, what's the type of this function?
443 If you then apply this `blackhole` function to an argument,
447 the interpreter goes into an infinite loop, and you have to type control-c
450 Oh, one more thing: lambda expressions look like this:
454 # (fun x -> x) true;;
457 (But `(fun x -> x x)` still won't work.)
459 You may also see this:
461 # (function x -> x);;
464 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.
466 We can try our usual tricks:
468 # (fun x -> true) blackhole;;
471 OCaml declined to try to fully reduce the argument before applying the
472 lambda function. Question: Why is that? Didn't we say that OCaml is a call-by-value/eager language?
474 Remember that `blackhole` is a function too, so we can
475 reverse the order of the arguments:
477 # blackhole (fun x -> true);;
481 Now consider the following variations in behavior:
483 # let test = blackhole blackhole;;
484 <Infinite loop, need to control-c to interrupt>
486 # let test () = blackhole blackhole;;
487 val test : unit -> 'a = <fun>
490 - : unit -> 'a = <fun>
493 <Infinite loop, need to control-c to interrupt>
495 We can use functions that take arguments of type `unit` to control
496 execution. In Scheme parlance, functions on the `unit` type are called
497 *thunks* (which I've always assumed was a blend of "think" and "chunk").
499 Question: why do thunks work? We know that `blackhole ()` doesn't terminate, so why do expressions like:
501 let f = fun () -> blackhole ()
506 Bottom type, divergence
507 -----------------------
509 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:
511 type 'a option = None | Some of 'a;;
512 type 'a option = None | Some of 'a | bottom;;
514 Here are some exercises that may help better understand this. Figure out what is the type of each of the following:
522 let rec blackhole x = blackhole x in blackhole;;
524 let rec blackhole x = blackhole x in blackhole 1;;
526 let rec blackhole x = blackhole x in fun (y:int) -> blackhole y y y;;
528 let rec blackhole x = blackhole x in (blackhole 1) + 2;;
530 let rec blackhole x = blackhole x in (blackhole 1) || false;;
532 let rec blackhole x = blackhole x in 2 :: (blackhole 1);;
534 By the way, what's the type of this:
536 let rec blackhole (x:'a) : 'a = blackhole x in blackhole
539 Back to thunks: the reason you'd want to control evaluation with
540 thunks is to manipulate when "effects" happen. In a strongly
541 normalizing system, like the simply-typed lambda calculus or System F,
542 there are no "effects." In Scheme and OCaml, on the other hand, we can
543 write programs that have effects. One sort of effect is printing.
544 Another sort of effect is mutation, which we'll be looking at soon.
545 Continuations are yet another sort of effect. None of these are yet on
546 the table though. The only sort of effect we've got so far is
547 *divergence* or non-termination. So the only thing thunks are useful
548 for yet is controlling whether an expression that would diverge if we
549 tried to fully evaluate it does diverge. As we consider richer
550 languages, thunks will become more useful.