e15a34d8833c54a7942005aea9f834570acce2db
[lambda.git] / topics / _week5_simply_typed_lambda.mdwn
1 [[!toc]]
2
3 ##The simply-typed lambda calculus##
4
5 The untyped lambda calculus is pure.  Pure in many ways: nothing but
6 variables and lambdas, with no constants or other special symbols;
7 also, all functions without any types.  As we'll see eventually, pure
8 also in the sense of having no side effects, no mutation, just pure
9 computation.
10
11 But we live in an impure world.  It is much more common for practical
12 programming languages to be typed, either implicitly or explicitly.
13 Likewise, systems used to investigate philosophical or linguistic
14 issues are almost always typed.  Types will help us reason about our
15 computations.  They will also facilitate a connection between logic
16 and computation.
17
18 From a linguistic perspective, types are generalizations of (parts of)
19 programs.  To make this comment more concrete: types are to (e.g.,
20 lambda) terms as syntactic categories are to expressions of natural
21 language.  If so, if it makes sense to gather a class of expressions
22 together into a set of Nouns, or Verbs, it may also make sense to
23 gather classes of terms into a set labelled with some computational type.
24
25 To develop this analogy just a bit further, syntactic categories
26 determine which expressions can combine with which other expressions.
27 If a word is a member of the category of prepositions, it had better
28 not try to combine (merge) with an expression in the category of, say,
29 an auxilliary verb, since *under has* is not a well-formed constituent
30 in English.  Likewise, types in formal languages will determine which
31 expressions can be sensibly combined. 
32
33 Now, of course it is common linguistic practice to supply an analysis
34 of natural language both with syntactic categories and with semantic
35 types.  And there is a large degree of overlap between these type
36 systems.  However, there are mismatches in both directions: there are
37 syntactic distinctions that do not correspond to any salient semantic
38 difference (why can't adjectives behave syntactically like verb
39 phrases, since they both denote properties with (extensional) type
40 `<e,t>`?); and in some analyses there are semantic differences that do
41 not correspond to any salient syntactic distinctions (as in any
42 analysis that involves silent type-shifters, such as Herman Hendriks'
43 theory of quantifier scope, in which expressions change their semantic
44 type without any effect on the syntactic expressions they can combine
45 with syntactically).  We will consider again the relationship between
46 syntactic types and semantic types later in the course.
47
48 Soon we will consider polymorphic type systems.  First, however, we
49 will consider the simply-typed lambda calculus.  
50
51 [Pedantic on.  Why "*simply* typed"?  Well, the type system is
52 particularly simple.  As mentioned to us by Koji Mineshima, Church
53 tells us that "The simple theory of types was suggested as a
54 modification of Russell's ramified theory of types by Leon Chwistek in
55 1921 and 1922 and by F. P. Ramsey in 1926."  This footnote appears in
56 Church's 1940 paper [A formulation of the simple theory of
57 types](church-simple-types.pdf).  In this paper, Church writes types
58 by simple apposition, without the ugly angle brackets and commas used
59 by Montague.  Furthermore, he omits parentheses under the convention
60 that types associated to the *left*---the opposite of the modern
61 convention.  This is ok, however, because he also reverses the order,
62 so that `te` is a function from objects of type `e` to objects of type
63 `t`.  Cool paper!  If you ever want to see Church numerals in their
64 native setting--but I'm getting ahead of my story.  Pedantic off.]
65
66 There's good news and bad news: the good news is that the simply-typed
67 lambda calculus is strongly normalizing: every term has a normal form.
68 We shall see that self-application is outlawed, so &Omega; can't even
69 be written, let alone undergo reduction.  The bad news is that
70 fixed-point combinators are also forbidden, so recursion is neither
71 simple nor direct.
72
73 #Types#
74
75 We will have at least one ground type.  For the sake of linguistic
76 familiarity, we'll use `e`, the type of individuals, and `t`, the type
77 of truth values.
78
79 In addition, there will be a recursively-defined class of complex
80 types `T`, the smallest set such that
81
82 *    ground types, including `e` and `t`, are in `T`
83
84 *    for any types &sigma; and &tau; in `T`, the type &sigma; ->
85      &tau; is in `T`.
86
87 For instance, here are some types in `T`:
88
89      e
90      e -> t
91      e -> e -> t
92      (e -> t) -> t
93      (e -> t) -> e -> t
94
95 and so on.
96
97 #Typed lambda terms#
98
99 Given a set of types `T`, we define the set of typed lambda terms <code>&Lambda;_T</code>,
100 which is the smallest set such that
101
102 *    each type `t` has an infinite set of distinct variables, {x^t}_1,
103      {x^t}_2, {x^t}_3, ...
104
105 *    If a term `M` has type &sigma; -> &tau;, and a term `N` has type
106      &sigma;, then the application `(M N)` has type &tau;.
107
108 *    If a variable `a` has type &sigma;, and term `M` has type &tau;, 
109      then the abstract <code>&lambda; a M</code> has type &sigma; -> &tau;.
110
111 The definitions of types and of typed terms should be highly familiar
112 to semanticists, except that instead of writing &sigma; -> &tau;,
113 linguists write <&sigma;, &tau;>.  We will use the arrow notation,
114 since it is more iconic.
115
116 Some examples (assume that `x` has type `o`):
117
118       x            o
119       \x.x         o -> o
120       ((\x.x) x)   o
121
122 Excercise: write down terms that have the following types:
123
124                    o -> o -> o
125                    (o -> o) -> o -> o
126                    (o -> o -> o) -> o
127
128 #Associativity of types versus terms#
129
130 As we have seen many times, in the lambda calculus, function
131 application is left associative, so that `f x y z == (((f x) y) z)`.
132 Types, *THEREFORE*, are right associative: if `x`, `y`, and `z`
133 have types `a`, `b`, and `c`, respectively, then `f` has type 
134 `a -> b -> c -> d == (a -> (b -> (c -> d)))`, where `d` is the
135 type of the complete term.
136
137 It is a serious faux pas to associate to the left for types.  You may
138 as well use your salad fork to stir your tea.
139
140 #The simply-typed lambda calculus is strongly normalizing#
141
142 If `M` is a term with type &tau; in &Lambda;_T, then `M` has a
143 normal form.  The proof is not particularly complex, but we will not
144 present it here; see Berendregt or Hankin.
145
146 Since &Omega; does not have a normal form, it follows that &Omega;
147 cannot have a type in &Lambda;_T.  We can easily see why:
148
149 <code>&Omega; = (\x.xx)(\x.xx)</code>
150
151 Assume &Omega; has type &tau;, and `\x.xx` has type &sigma;.  Then
152 because `\x.xx` takes an argument of type &sigma; and returns
153 something of type &tau;, `\x.xx` must also have type &sigma; ->
154 &tau;.  By repeating this reasoning, `\x.xx` must also have type
155 (&sigma; -> &tau;) -> &tau;; and so on.  Since variables have
156 finite types, there is no way to choose a type for the variable `x`
157 that can satisfy all of the requirements imposed on it.
158
159 In general, there is no way for a function to have a type that can
160 take itself for an argument.  It follows that there is no way to
161 define the identity function in such a way that it can take itself as
162 an argument.  Instead, there must be many different identity
163 functions, one for each type.  Some of those types can be functions,
164 and some of those functions can be (type-restricted) identity
165 functions; but a simply-types identity function can never apply to itself.
166
167 #Typing numerals#
168
169 The Church numerals are well behaved with respect to types.  
170 To see this, consider the first three Church numerals (starting with zero):
171
172     \s z . z
173     \s z . s z
174     \s z . s (s z)
175
176 Given the internal structure of the term we are using to represent
177 zero, its type must have the form &rho; -> &sigma; -> &sigma; for
178 some &rho; and &sigma;.  This type is consistent with term for one,
179 but the structure of the definition of one is more restrictive:
180 because the first argument (`s`) must apply to the second argument
181 (`z`), the type of the first argument must describe a function from
182 expressions of type &sigma; to some result type.  So we can refine
183 &rho; by replacing it with the more specific type &sigma; -> &tau;.
184 At this point, the overall type is (&sigma; -> &tau;) -> &sigma; ->
185 &sigma;.  Note that this refined type remains compatible with the
186 definition of zero.  Finally, by examinining the definition of two, we
187 see that expressions of type &tau; must be suitable to serve as
188 arguments to functions of type &sigma; -> &tau;, since the result of
189 applying `s` to `z` serves as the argument of `s`.  The most general
190 way for that to be true is if &tau; &equiv; &sigma;.  So at this
191 point, we have the overall type of (&sigma; -> &sigma;) -> &sigma;
192 -> &sigma;.
193
194 <!-- Make sure there is talk about unification and computation of the
195 principle type-->
196
197 ## Predecessor and lists are not representable in simply typed lambda-calculus ##
198
199 As Oleg Kiselyov points out, [[predecessor and lists can't be
200 represented in the simply-typed lambda
201 calculus|http://okmij.org/ftp/Computation/lambda-calc.html#predecessor]].
202 This is not because there is any difficulty typing what the functions
203 involved do "from the outside": for instance, the predecessor function
204 is a function from numbers to numbers, or &tau; -> &tau;, where &tau;
205 is our type for Church numbers (i.e., (&sigma; -> &sigma;) -> &sigma;
206 -> &sigma;).  (Though this type will only be correct if we decide that
207 the predecessor of zero should be a number, perhaps zero.)
208
209 Rather, the problem is that the definition of the function requires
210 subterms that can't be simply-typed.  We'll illustrate with our
211 implementation of the predecessor, sightly modified in inessential
212 ways to suit present purposes:
213
214     let zero = \s z. z in
215     let snd = \a b. b in
216     let pair = \a b. \v. v a b in
217     let succ = \n s z. s (n s z) in
218     let collect = \p. p (\a b. pair (succ a) a)
219     let pred = \n. n collect (pair zero zero) snd in
220
221 Let's see how far we can get typing these terms.  `zero` is the Church
222 encoding of zero.  Using `N` as the type for Church numbers (i.e.,
223 <code>N &equiv; (&sigma; -> &sigma;) -> &sigma; -> &sigma;</code> for some
224 &sigma;, `zero` has type `N`.  `snd` takes two numbers, and returns
225 the second, so `snd` has type `N -> N -> N`.  Then the type of `pair`
226 is `N -> N -> (type(snd)) -> N`, that is, `N -> N -> (N -> N -> N) ->
227 N`.  Likewise, `succ` has type `N -> N`, and `collect` has type `pair
228 -> pair`, where `pair` is the type of an ordered pair of numbers,
229 namely, <code>pair &equiv; (N -> N -> N) -> N</code>.  So far so good.
230
231 The problem is the way in which `pred` puts these parts together.  In
232 particular, `pred` applies its argument, the number `n`, to the
233 `collect` function.  Since `n` is a number, its type is <code>(&sigma;
234 -> &sigma;) -> &sigma; -> &sigma;</code>.  This means that the type of
235 `collect` has to match <code>&sigma; -> &sigma;</code>. But we
236 concluded above that the type of `collect` also had to be `pair ->
237 pair`.  Putting these constraints together, it appears that
238 <code>&sigma;</code> must be the type of a pair of numbers.  But we
239 already decided that the type of a pair of numbers is `(N -> N -> N)
240 -> N`.  Here's the difficulty: `N` is shorthand for a type involving
241 <code>&sigma;</code>.  If <code>&sigma;</code> turns out to depend on
242 `N`, and `N` depends in turn on <code>&sigma;</code>, then
243 <code>&sigma;</code> is a proper subtype of itself, which is not
244 allowed in the simply-typed lambda calculus.
245
246 The way we got here is that the `pred` function relies on the built-in
247 right-fold structure of the Church numbers to recursively walk down
248 the spine of its argument.  In order to do that, the argument had to
249 apply to the `collect` operation.  And since `collect` had to be the
250 sort of operation that manipulates numbers, the infinite regress is
251 established.
252
253 Now, of course, this is only one of myriad possible implementations of
254 the predecessor function in the lambda calculus.  Could one of them
255 possibly be simply-typeable?  It turns out that this can't be done.
256 See the works cited by Oleg for details.
257
258 Because lists are (in effect) a generalization of the Church numbers,
259 computing the tail of a list is likewise beyond the reach of the
260 simply-typed lambda calculus.
261
262 This result is surprising.  It illustrates how recursion is built into
263 the structure of the Church numbers (and lists).  Most importantly for
264 the discussion of the simply-typed lambda calculus, it demonstrates
265 that even fairly basic recursive computations are beyond the reach of
266 a simply-typed system.
267
268
269 ## Montague grammar is based on a simply-typed lambda calculus
270
271 Systems based on the simply-typed lambda calculus are the bread and
272 butter of current linguistic semantic analysis.  One of the most
273 influential modern semantic formalisms---Montague's PTQ
274 fragment---included a simply-typed version of the Predicate Calculus
275 with lambda abstraction.
276
277 Montague called the semantic part of his PTQ fragment *Intensional
278 Logic*.  Without getting too fussy about details, we'll present the
279 popular Ty2 version of the PTQ types, roughly as proposed by Gallin
280 (1975).  [See Zimmermann, Ede. 1989. Intensional logic and two-sorted
281 type theory.  *Journal of Symbolic Logic* ***54.1***: 65--77 for a
282 precise characterization of the correspondence between IL and
283 two-sorted Ty2.]
284
285 We'll need three base types: `e`, for individuals, `t`, for truth
286 values, and `s` for evaluation indicies (world-time pairs).  The set
287 of types is defined recursively:
288
289     the base types e, t, and s are types
290     if a and b are types, <a,b> is a type
291
292 So `<e,<e,t>>` and `<s,<<s,e>,t>>` are types.  As we have mentioned,
293 this paper is the source for the convention in linguistics that a type
294 of the form `<a, b>` corresponds to a functional type that we will
295 write here as `a -> b`.  So the type `<a,b>` is the type of a function
296 that maps objects of type `a` onto objects of type `b`.
297
298 Montague gave rules for the types of various logical formulas.  Of
299 particular interest here, he gave the following typing rules for
300 functional application and for lambda abstracts:
301
302 * If *&alpha;* is an expression of type *<a, b>*, and *&beta;* is an
303 expression of type b, then *&alpha;(&beta;)* has type *b*.  
304
305 * If &alpha;* is an expression of type *a*, and *u* is a variable of
306 *type b*, then *&lambda;u&alpha;* has type <code><b, a></code>.
307
308 When we talk about monads, we will consider Montague's treatment of
309 intensionality in some detail.  In the meantime, Montague's PTQ is
310 responsible for making the simply-typed lambda calculus the baseline
311 semantic analysis for linguistics.