(no commit message)
[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 function, based on the discussion in
212 Pierce 2002:547:
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 shift = \p. p (\a b. pair (succ a) a)
219     let pred = \n. n shift (pair zero zero) snd in
220
221 Note that `shift` applies its argument p ("p" for "pair") to a
222 function that ignores its second argument---why does it do that?  In
223 order to understand what this code is doing, it is helpful to go
224 through a sample computation, the predecessor of 3:
225
226     pred (\s z.s(s(s z)))
227     (\s z.s(s(s z))) (\n.n shift (\f.f 0 0) snd)
228     shift (shift (shift (\f.f 0 0))) snd
229     shift (shift ((\f.f 0 0) (\a b.pair(succ a) a))) snd
230     shift (shift (\f.f 1 0)) snd
231     shift (\f. f 2 1) snd
232     (\f. f 3 2) snd
233     2
234
235 At each stage, `shift` sees an ordered pair that contains two numbers
236 related by the successor function.  It can safely discard the second
237 element without losing any information.  The reason we carry around
238 the second element at all is that when it comes time to complete the
239 computation---that is, when we finally apply the top-level ordered
240 pair to `snd`---it's the second element of the pair that will serve as
241 the final result.
242
243 Let's see how far we can get typing these terms.  `zero` is the Church
244 encoding of zero.  Using `N` as the type for Church numbers (i.e.,
245 <code>N &equiv; (&sigma; -> &sigma;) -> &sigma; -> &sigma;</code> for
246 some &sigma;, `zero` has type `N`.  `snd` takes two numbers, and
247 returns the second, so `snd` has type `N -> N -> N`.  Then the type of
248 `pair` is `N -> N -> (type(snd)) -> N`, that is, `N -> N -> (N -> N ->
249 N) -> N`.  Likewise, `succ` has type `N -> N`, and `shift` has type
250 `pair -> pair`, where `pair` is the type of an ordered pair of
251 numbers, namely, <code>pair &equiv; (N -> N -> N) -> N</code>.  So far
252 so good.
253
254 The problem is the way in which `pred` puts these parts together.  In
255 particular, `pred` applies its argument, the number `n`, to the
256 `shift` function.  Since `n` is a number, its type is <code>(&sigma;
257 -> &sigma;) -> &sigma; -> &sigma;</code>.  This means that the type of
258 `shift` has to match <code>&sigma; -> &sigma;</code>. But we
259 concluded above that the type of `shift` also had to be `pair ->
260 pair`.  Putting these constraints together, it appears that
261 <code>&sigma;</code> must be the type of a pair of numbers.  But we
262 already decided that the type of a pair of numbers is `(N -> N -> N)
263 -> N`.  Here's the difficulty: `N` is shorthand for a type involving
264 <code>&sigma;</code>.  If <code>&sigma;</code> turns out to depend on
265 `N`, and `N` depends in turn on <code>&sigma;</code>, then
266 <code>&sigma;</code> is a proper subtype of itself, which is not
267 allowed in the simply-typed lambda calculus.
268
269 The way we got here is that the `pred` function relies on the built-in
270 right-fold structure of the Church numbers to recursively walk down
271 the spine of its argument.  In order to do that, the argument had to
272 apply to the `shift` operation.  And since `shift` had to be the
273 sort of operation that manipulates numbers, the infinite regress is
274 established.
275
276 Now, of course, this is only one of myriad possible implementations of
277 the predecessor function in the lambda calculus.  Could one of them
278 possibly be simply-typeable?  It turns out that this can't be done.
279 See the works cited by Oleg for details.
280
281 Because lists are (in effect) a generalization of the Church numbers,
282 computing the tail of a list is likewise beyond the reach of the
283 simply-typed lambda calculus.
284
285 This result is not obvious, to say the least.  It illustrates how
286 recursion is built into the structure of the Church numbers (and
287 lists).  Most importantly for the discussion of the simply-typed
288 lambda calculus, it demonstrates that even fairly basic recursive
289 computations are beyond the reach of a simply-typed system.
290
291
292 ## Montague grammar is based on a simply-typed lambda calculus
293
294 Systems based on the simply-typed lambda calculus are the bread and
295 butter of current linguistic semantic analysis.  One of the most
296 influential modern semantic formalisms---Montague's PTQ
297 fragment---included a simply-typed version of the Predicate Calculus
298 with lambda abstraction.
299
300 Montague called the semantic part of his PTQ fragment *Intensional
301 Logic*.  Without getting too fussy about details, we'll present the
302 popular Ty2 version of the PTQ types, roughly as proposed by Gallin
303 (1975).  [See Zimmermann, Ede. 1989. Intensional logic and two-sorted
304 type theory.  *Journal of Symbolic Logic* ***54.1***: 65--77 for a
305 precise characterization of the correspondence between IL and
306 two-sorted Ty2.]
307
308 We'll need three base types: `e`, for individuals, `t`, for truth
309 values, and `s` for evaluation indicies (world-time pairs).  The set
310 of types is defined recursively:
311
312     the base types e, t, and s are types
313     if a and b are types, <a,b> is a type
314
315 So `<e,<e,t>>` and `<s,<<s,e>,t>>` are types.  As we have mentioned,
316 this paper is the source for the convention in linguistics that a type
317 of the form `<a, b>` corresponds to a functional type that we will
318 write here as `a -> b`.  So the type `<a,b>` is the type of a function
319 that maps objects of type `a` onto objects of type `b`.
320
321 Montague gave rules for the types of various logical formulas.  Of
322 particular interest here, he gave the following typing rules for
323 functional application and for lambda abstracts:
324
325 * If *&alpha;* is an expression of type *<a, b>*, and *&beta;* is an
326 expression of type b, then *&alpha;(&beta;)* has type *b*.  
327
328 * If *&alpha;* is an expression of type *a*, and *u* is a variable of type *b*, then *&lambda;u&alpha;* has type <code><b, a></code>.
329
330 When we talk about monads, we will consider Montague's treatment of
331 intensionality in some detail.  In the meantime, Montague's PTQ is
332 responsible for making the simply-typed lambda calculus the baseline
333 semantic analysis for linguistics.