week7: use u,v for monadic terms
[lambda.git] / week7.mdwn
1 [[!toc]]
2
3
4 Monads
5 ------
6
7 Start by (re)reading the discussion of monads in the lecture notes for
8 week 6 [[Towards Monads]].
9 In those notes, we saw a way to separate thinking about error
10 conditions (such as trying to divide by zero) from thinking about
11 normal arithmetic computations.  We did this by making use of the
12 option monad: in each place where we had something of type `int`, we
13 put instead something of type `int option`, which is a sum type
14 consisting either of just an integer, or else some special value which
15 we could interpret as signaling that something had gone wrong.
16
17 The goal was to make normal computing as convenient as possible: when
18 we're adding or multiplying, we don't have to worry about generating
19 any new errors, so we do want to think about the difference between
20 `int`s and `int option`s.  We tried to accomplish this by defining a
21 `bind` operator, which enabled us to peel away the `option` husk to get
22 at the delicious integer inside.  There was also a homework problem
23 which made this even more convenient by mapping any binary operation
24 on plain integers into a lifted operation that understands how to deal
25 with `int option`s in a sensible way.
26
27 [Linguitics note: Dividing by zero is supposed to feel like a kind of
28 presupposition failure.  If we wanted to adapt this approach to
29 building a simple account of presupposition projection, we would have
30 to do several things.  First, we would have to make use of the
31 polymorphism of the `option` type.  In the arithmetic example, we only
32 made use of `int option`s, but when we're composing natural language
33 expression meanings, we'll need to use types like `N option`, `Det option`,
34 `VP option`, and so on.  But that works automatically, because we can use
35 any type for the `'a` in `'a option`.  Ultimately, we'd want to have a
36 theory of accommodation, and a theory of the situations in which
37 material within the sentence can satisfy presuppositions for other
38 material that otherwise would trigger a presupposition violation; but,
39 not surprisingly, these refinements will require some more
40 sophisticated techniques than the super-simple option monad.]
41
42 So what exactly is a monad?  As usual, we're not going to be pedantic
43 about it, but for our purposes, we can consider a monad to be a system
44 that provides at least the following three elements:
45
46 *       A complex type that's built around some more basic type. Usually
47         it will be polymorphic, and so can apply to different basic types.
48         In our division example, the polymorphism of the `'a option` type
49         provides a way of building an option out of any other type of object.
50         People often use a container metaphor: if `x` has type `int option`,
51         then `x` is a box that (may) contain an integer.
52
53                 type 'a option = None | Some of 'a;;
54
55 *       A way to turn an ordinary value into a monadic value.  In OCaml, we
56         did this for any integer `x` by mapping it to
57         the option `Some x`.  In the general case, this operation is
58         known as `unit` or `return.` Both of those names are terrible. This
59         operation is only very loosely connected to the `unit` type we were
60         discussing earlier (whose value is written `()`). It's also only
61         very loosely connected to the "return" keyword in many other
62         programming languages like C. But these are the names that the literature
63         uses.
64
65         The unit/return operation is a way of lifting an ordinary object into
66         the monadic box you've defined, in the simplest way possible. You can think
67         of the singleton function as an example: it takes an ordinary object
68         and returns a set containing that object. In the example we've been
69         considering:
70
71                 let unit x = Some x;;
72                 val unit : 'a -> 'a option = <fun>
73
74         So `unit` is a way to put something inside of a monadic box. It's crucial
75         to the usefulness of monads that there will be monadic boxes that
76         aren't the result of that operation. In the option/maybe monad, for
77         instance, there's also the empty box `None`. In another (whimsical)
78         example, you might have, in addition to boxes merely containing integers,
79         special boxes that contain integers and also sing a song when they're opened. 
80
81         The unit/return operation will always be the simplest, conceptually
82         most straightforward way to lift an ordinary value into a monadic value
83         of the monadic type in question.
84
85 *       Thirdly, an operation that's often called `bind`. This is another
86         unfortunate name: this operation is only very loosely connected to
87         what linguists usually mean by "binding." In our option/maybe monad, the
88         bind operation is:
89
90                 let bind u f = match u with None -> None | Some x -> f x;;
91                 val bind : 'a option -> ('a -> 'b option) -> 'b option = <fun>
92
93         Note the type. `bind` takes two arguments: first, a monadic "box"
94         (in this case, an 'a option); and second, a function from
95         ordinary objects to monadic boxes. `bind` then returns a monadic
96         value: in this case, a 'b option (you can start with, e.g., int options
97         and end with bool options).
98
99         Intuitively, the interpretation of what `bind` does is like this:
100         the first argument is a monadic value u, which 
101         evaluates to a box that (maybe) contains some ordinary value, call it `x`.
102         Then the second argument uses `x` to compute a new monadic
103         value.  Conceptually, then, we have
104
105                 let bind u f = (let x = unbox u in f x);;
106
107         The guts of the definition of the `bind` operation amount to
108         specifying how to unbox the monadic value `u`.  In the bind
109         opertor for the option monad, we unboxed the option monad by
110         matching the monadic value `u` with `Some x`---whenever `u`
111         happened to be a box containing an integer `x`, this allowed us to
112         get our hands on that `x` and feed it to `f`.
113
114         If the monadic box didn't contain any ordinary value, then
115         we just pass through the empty box unaltered.
116
117         In a more complicated case, like our whimsical "singing box" example
118         from before, if the monadic value happened to be a singing box
119         containing an integer `x`, then the `bind` operation would probably
120         be defined so as to make sure that the result of `f x` was also
121         a singing box. If `f` also inserted a song, you'd have to decide
122         whether both songs would be carried through, or only one of them.
123
124         There is no single `bind` function that dictates how this must go.
125         For each new monadic type, this has to be worked out in an
126         useful way.
127
128 So the "option/maybe monad" consists of the polymorphic option type, the
129 unit/return function, and the bind function.  With the option monad, we can
130 think of the "safe division" operation
131
132 <pre>
133 # let divide' num den = if den = 0 then None else Some (num/den);;
134 val divide' : int -> int -> int option = <fun>
135 </pre>
136
137 as basically a function from two integers to an integer, except with
138 this little bit of option plumbing on the side.
139
140 A note on notation: Haskell uses the infix operator `>>=` to stand
141 for `bind`. Chris really hates that symbol.  Following Wadler, he prefers to
142 use an infix five-pointed star, or on a keyboard, `*`. Jim on the other hand
143 thinks `>>=` is what the literature uses and students won't be able to
144 avoid it. Moreover, although &#8902; is OK (though not a convention that's been picked up), overloading the multiplication symbol invites its own confusion
145 and Jim feels very uneasy about that. If not `>>=` then we should use
146 some other unfamiliar infix symbol (but `>>=` already is such...)
147
148 In any case, the course leaders will work this out somehow. In the meantime,
149 as you read around, wherever you see `u >>= f`, that means `bind u f`. Also,
150 if you ever see this notation:
151
152         do
153                 x <- u
154                 f x
155
156 That's a Haskell shorthand for `u >>= (\x -> f x)`, that is, `bind u f`.
157 Similarly:
158
159         do
160                 x <- u
161                 y <- v
162                 f x y
163
164 is shorthand for `u >>= (\x -> v >>= (\y -> f x y))`, that is, `bind u (fun x
165 -> bind v (fun y -> f x y))`. Those who did last week's homework may recognize
166 this.
167
168 (Note that the above "do" notation comes from Haskell. We're mentioning it here
169 because you're likely to see it when reading about monads. It won't work in
170 OCaml. In fact, the `<-` symbol already means something different in OCaml,
171 having to do with mutable record fields. We'll be discussing mutation someday
172 soon.)
173
174 As we proceed, we'll be seeing a variety of other monad systems. For example, another monad is the list monad. Here the monadic type is:
175
176         # type 'a list
177
178 The unit/return operation is:
179
180         # let unit x = [x];;
181         val unit : 'a -> 'a list = <fun>
182
183 That is, the simplest way to lift an 'a into an 'a list is just to make a
184 singleton list of that 'a. Finally, the bind operation is:
185
186         # let bind u f = List.concat (List.map f u);;
187         val bind : 'a list -> ('a -> 'b list) -> 'b list = <fun>
188         
189 What's going on here? Well, consider (List.map f u) first. This goes through all
190 the members of the list u. There may be just a single member, if `u = unit a`
191 for some a. Or on the other hand, there may be no members, or many members. In
192 any case, we go through them in turn and feed them to f. Anything that gets fed
193 to f will be an 'a. f takes those values, and for each one, returns a 'b list.
194 For example, it might return a list of all that value's divisors. Then we'll
195 have a bunch of 'b lists. The surrounding `List.concat ( )` converts that bunch
196 of 'b lists into a single 'b list:
197
198         # List.concat [[1]; [1;2]; [1;3]; [1;2;4]]
199         - : int list = [1; 1; 2; 1; 3; 1; 2; 4]
200
201 So now we've seen two monads: the option/maybe monad, and the list monad. For any
202 monadic system, there has to be a specification of the complex monad type,
203 which will be parameterized on some simpler type 'a, and the unit/return
204 operation, and the bind operation. These will be different for different
205 monadic systems.
206
207 Many monadic systems will also define special-purpose operations that only make
208 sense for that system.
209
210 Although the unit and bind operation are defined differently for different
211 monadic systems, there are some general rules they always have to follow.
212
213
214 The Monad Laws
215 --------------
216
217 Just like good robots, monads must obey three laws designed to prevent
218 them from hurting the people that use them or themselves.
219
220 *       **Left identity: unit is a left identity for the bind operation.**
221         That is, for all `f:'a -> 'a m`, where `'a m` is a monadic
222         value, we have `(unit x) * f == f x`.  For instance, `unit` is itself
223         a function of type `'a -> 'a m`, so we can use it for `f`:
224
225 <pre>
226 # let ( * ) u f = match u with None -> None | Some x -> f x;;
227 val ( * ) : 'a option -> ('a -> 'b option) -> 'b option = <fun>
228 # let unit x = Some x;;
229 val unit : 'a -> 'a option = <fun>
230
231 # unit 2;;
232 - : int option = Some 2
233 # unit 2 * unit;;
234 - : int option = Some 2
235
236 # divide 6 2;;
237 - : int option = Some 3
238 # unit 2 * divide 6;;
239 - : int option = Some 3
240
241 # divide 6 0;;
242 - : int option = None
243 # unit 0 * divide 6;;
244 - : int option = None
245 </pre>
246
247 The parentheses is the magic for telling OCaml that the
248 function to be defined (in this case, the name of the function
249 is `*`, pronounced "bind") is an infix operator, so we write
250 `u * f` or `( * ) u f` instead of `* u f`.
251
252 *       **Associativity: bind obeys a kind of associativity**. Like this:
253
254                 (u * f) * g == u * (fun x -> f x * g)
255
256         If you don't understand why the lambda form is necessary (the "fun
257         x" part), you need to look again at the type of bind.
258
259         Some examples of associativity in the option monad:
260
261 <pre>
262 # Some 3 * unit * unit;; 
263 - : int option = Some 3
264 # Some 3 * (fun x -> unit x * unit);;
265 - : int option = Some 3
266
267 # Some 3 * divide 6 * divide 2;;
268 - : int option = Some 1
269 # Some 3 * (fun x -> divide 6 x * divide 2);;
270 - : int option = Some 1
271
272 # Some 3 * divide 2 * divide 6;;
273 - : int option = None
274 # Some 3 * (fun x -> divide 2 x * divide 6);;
275 - : int option = None
276 </pre>
277
278 Of course, associativity must hold for arbitrary functions of
279 type `'a -> 'a m`, where `m` is the monad type.  It's easy to
280 convince yourself that the bind operation for the option monad
281 obeys associativity by dividing the inputs into cases: if `u`
282 matches `None`, both computations will result in `None`; if
283 `u` matches `Some x`, and `f x` evalutes to `None`, then both
284 computations will again result in `None`; and if the value of
285 `f x` matches `Some y`, then both computations will evaluate
286 to `g y`.
287
288 *       **Right identity: unit is a right identity for bind.**  That is, 
289         `u * unit == u` for all monad objects `u`.  For instance,
290
291 <pre>
292 # Some 3 * unit;;
293 - : int option = Some 3
294 # None * unit;;
295 - : 'a option = None
296 </pre>
297
298
299 More details about monads
300 -------------------------
301
302 If you studied algebra, you'll remember that a *monoid* is an
303 associative operation with a left and right identity.  For instance,
304 the natural numbers along with multiplication form a monoid with 1
305 serving as the left and right identity.  That is, temporarily using
306 `*` to mean arithmetic multiplication, `1 * u == u == u * 1` for all
307 `u`, and `(u * v) * w == u * (v * w)` for all `u`, `v`, and `w`.  As
308 presented here, a monad is not exactly a monoid, because (unlike the
309 arguments of a monoid operation) the two arguments of the bind are of
310 different types.  But it's possible to make the connection between
311 monads and monoids much closer. This is discussed in [[Advanced Notes/Monads in Category Theory]]. See also <http://www.haskell.org/haskellwiki/Monad_Laws>.
312
313 Here are some papers that introduced monads into functional programming:
314
315 *       [Eugenio Moggi, Notions of Computation and Monads](http://www.disi.unige.it/person/MoggiE/ftp/ic91.pdf): Information and Computation 93 (1).
316
317 *       [Philip Wadler. Monads for Functional Programming](http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf):
318 in M. Broy, editor, *Marktoberdorf Summer School on Program Design Calculi*, Springer Verlag, NATO ASI Series F: Computer and systems sciences, Volume 118, August 1992. Also in J. Jeuring and E. Meijer, editors, *Advanced Functional Programming*, Springer Verlag, LNCS 925, 1995. Some errata fixed August 2001.
319         The use of monads to structure functional programs is described. Monads provide a convenient framework for simulating effects found in other languages, such as global state, exception handling, output, or non-determinism. Three case studies are looked at in detail: how monads ease the modification of a simple evaluator; how monads act as the basis of a datatype of arrays subject to in-place update; and how monads can be used to build parsers.
320
321 *       [Philip Wadler. The essence of functional programming](http://homepages.inf.ed.ac.uk/wadler/papers/essence/essence.ps):
322 invited talk, *19'th Symposium on Principles of Programming Languages*, ACM Press, Albuquerque, January 1992.
323         This paper explores the use monads to structure functional programs. No prior knowledge of monads or category theory is required.
324         Monads increase the ease with which programs may be modified. They can mimic the effect of impure features such as exceptions, state, and continuations; and also provide effects not easily achieved with such features. The types of a program reflect which effects occur.
325         The first section is an extended example of the use of monads. A simple interpreter is modified to support various extra features: error messages, state, output, and non-deterministic choice. The second section describes the relation between monads and continuation-passing style. The third section sketches how monads are used in a compiler for Haskell that is written in Haskell.
326
327 There's a long list of monad tutorials on the [[Offsite Reading]] page. Skimming the titles makes me laugh.
328
329 In the presentation we gave above, which is the usual one in functional programming, we took unit/return and bind as the primitive operations. From these a number of other general monad operations can be derived. It's also possible to take some of the others as primitive, and define for example bind in terms of them. This is discussed some in the [[Advanced Notes/Monads in Category Theory]].
330
331
332 Here are some of the specifics. You don't have to master these; they're collected here for your reference.
333
334 You may sometimes see:
335
336         u >> v
337
338 That just means:
339
340         u >>= fun _ -> v
341
342 that is:
343
344         bind u (fun _ -> v)
345
346 You could also do `bind u (fun x -> v)`; we use the `_` for the function argument to be explicit that that argument is never going to be used.
347
348 The `lift` operation we asked you to define for last week's homework is a common operation. The second argument to `bind` converts `'a` values into `'b m` values---that is, into instances of the monadic type. What if we instead had a function that merely converts `'a` values into `'b` values, and we want to use it with our monadic type. Then we "lift" that function into an operation on the monad. For example:
349
350         # let even x = (x mod 2 = 0);;
351         val g : int -> bool = <fun>
352
353 `even` has the type int -> bool. Now what if we want to convert it into an operation on the option/maybe monad?
354
355         # let lift g = fun u -> bind u (fun x -> Some (g x));;
356         val lift : ('a -> 'b) -> 'a option -> 'b option = <fun>
357
358 `lift even` will now be a function from `int option`s to `bool option`s. We can
359 also define a lift operation for binary functions:
360
361         # let lift2 g = fun u v -> bind u (fun x -> bind v (fun y -> Some (g x y)));;
362         val lift2 : ('a -> 'b -> 'c) -> 'a option -> 'b option -> 'c option = <fun>
363
364 `lift (+)` will now be a function from `int option`s  and `int option`s to `int option`s. This should look familiar to those who did the homework.
365
366 The `lift` operation (just `lift`, not `lift2`) is sometimes also called the `map` operation. (In Haskell, they say `fmap` or `<$>`.) And indeed when we're working with list monad, `lift f` is exactly `List.map f`!
367
368 Wherever we have a well-defined monad, we can define a lift/map operation for that monad. The examples above used `Some (g x)` and so on; in the general case we'd use `unit (g x)`, using the pre-defined `unit` operation for the monad we're working with.
369
370 In general, any lift/map operation can be relied on to satisfy these laws:
371
372         * lift id = id
373         * lift (compose f g) = compose (lift f) (lift g)
374
375 where id is `fun x -> x` and `compose a b` is `fun x -> a (b x)`. If you think about the special case of the map operation on lists, this should make sense. `List.map id lst` should give you back `lst` again. And you'd expect these
376 two computations to give the same result:
377
378         List.map (fun x -> f (g x)) lst
379
380         List.map f (List.map g lst)
381
382 Another general monad operation is called `ap` in Haskell---short for "apply." (They also use `<*>`, but who can remember that?) This works like this:
383
384         ap [f] [x; y] = [f x; f y]
385         ap (Some f) (Some x) = Some (f x)
386
387 and so on. Here are the laws that any ap operation can be relied on to satisfy:
388
389         ap (unit id) v = v
390         ap (ap (ap (return compose) u) v) w = ap u (ap v w)
391         ap (unit f) (unit x) = unit (f x)
392         ap u (unit y) = ap (unit (fun f -> f y)) u
393
394 Another general monad operation is called `join`. This is the operation that takes you from an iterated monad to a single monad. Remember when we were explaining the `bind` operation for the list monad, there was a step where
395 we went from:
396
397         [[1]; [1;2]; [1;3]; [1;2;4]]
398
399 to:
400
401         [1; 1; 2; 1; 3; 1; 2; 4]
402
403 That is the `join` operation.
404
405 All of these operations can be defined in terms of `bind` and `unit`; or alternatively, some of them can be taken as primitive and `bind` can be defined in terms of them. Here are various interdefinitions:
406
407         lift f u = ap (unit f) u
408         lift2 f u v = ap (lift f u) v = ap (ap (unit f) u) v
409         ap u v = lift2 id u v
410         lift f u = u >>= compose unit f
411         lift f u = ap (unit f) u
412         join m2 = m2 >>= id
413         u >>= f = join (lift f u)
414         u >> v = u >>= (fun _ -> v)
415         u >> v = lift2 (fun _ -> id) u v
416
417
418
419 Monad outlook
420 -------------
421
422 We're going to be using monads for a number of different things in the
423 weeks to come.  The first main application will be the State monad,
424 which will enable us to model mutation: variables whose values appear
425 to change as the computation progresses.  Later, we will study the
426 Continuation monad.
427
428 In the meantime, we'll look at several linguistic applications for monads, based
429 on what's called the *reader monad*.
430
431
432 The reader monad
433 ----------------
434
435 Introduce
436
437 Heim and Kratzer's "Predicate Abstraction Rule"
438
439
440
441 The intensionality monad
442 ------------------------
443 ...
444 intensional function application.  In Shan (2001) [Monads for natural
445 language semantics](http://arxiv.org/abs/cs/0205026v1), Ken shows that
446 making expressions sensitive to the world of evaluation is
447 conceptually the same thing as making use of a *reader monad* (which
448 we'll see again soon).  This technique was beautifully re-invented
449 by Ben-Avi and Winter (2007) in their paper [A modular
450 approach to
451 intensionality](http://parles.upf.es/glif/pub/sub11/individual/bena_wint.pdf),
452 though without explicitly using monads.
453
454 All of the code in the discussion below can be found here: [[intensionality-monad.ml]].
455 To run it, download the file, start OCaml, and say 
456
457         # #use "intensionality-monad.ml";;
458
459 Note the extra `#` attached to the directive `use`.
460
461 Here's the idea: since people can have different attitudes towards
462 different propositions that happen to have the same truth value, we
463 can't have sentences denoting simple truth values.  If we did, then if John
464 believed that the earth was round, it would force him to believe
465 Fermat's last theorem holds, since both propositions are equally true.
466 The traditional solution is to allow sentences to denote a function
467 from worlds to truth values, what Montague called an intension.  
468 So if `s` is the type of possible worlds, we have the following
469 situation:
470
471
472 <pre>
473 Extensional types                 Intensional types       Examples
474 -------------------------------------------------------------------
475
476 S         s->t                    s->t                    John left
477 DP        s->e                    s->e                    John
478 VP        s->e->t                 s->(s->e)->t            left
479 Vt        s->e->e->t              s->(s->e)->(s->e)->t    saw
480 Vs        s->t->e->t              s->(s->t)->(s->e)->t    thought
481 </pre>
482
483 This system is modeled on the way Montague arranged his grammar.
484 There are significant simplifications: for instance, determiner
485 phrases are thought of as corresponding to individuals rather than to
486 generalized quantifiers.  If you're curious about the initial `s`'s
487 in the extensional types, they're there because the behavior of these
488 expressions depends on which world they're evaluated at.  If you are
489 in a situation in which you can hold the evaluation world constant,
490 you can further simplify the extensional types.  Usually, the
491 dependence of the extension of an expression on the evaluation world
492 is hidden in a superscript, or built into the lexical interpretation
493 function.
494
495 The main difference between the intensional types and the extensional
496 types is that in the intensional types, the arguments are functions
497 from worlds to extensions: intransitive verb phrases like "left" now
498 take intensional concepts as arguments (type s->e) rather than plain
499 individuals (type e), and attitude verbs like "think" now take
500 propositions (type s->t) rather than truth values (type t).
501
502 The intenstional types are more complicated than the intensional
503 types.  Wouldn't it be nice to keep the complicated types to just
504 those attitude verbs that need to worry about intensions, and keep the
505 rest of the grammar as extensional as possible?  This desire is
506 parallel to our earlier desire to limit the concern about division by
507 zero to the division function, and let the other functions, like
508 addition or multiplication, ignore division-by-zero problems as much
509 as possible.
510
511 So here's what we do:
512
513 In OCaml, we'll use integers to model possible worlds:
514
515         type s = int;;
516         type e = char;;
517         type t = bool;;
518
519 Characters (characters in the computational sense, i.e., letters like
520 `'a'` and `'b'`, not Kaplanian characters) will model individuals, and
521 OCaml booleans will serve for truth values.
522
523 <pre>
524 type 'a intension = s -> 'a;;
525 let unit x (w:s) = x;;
526
527 let ann = unit 'a';;
528 let bill = unit 'b';;
529 let cam = unit 'c';;
530 </pre>
531
532 In our monad, the intension of an extensional type `'a` is `s -> 'a`,
533 a function from worlds to extensions.  Our unit will be the constant
534 function (an instance of the K combinator) that returns the same
535 individual at each world.
536
537 Then `ann = unit 'a'` is a rigid designator: a constant function from
538 worlds to individuals that returns `'a'` no matter which world is used
539 as an argument.
540
541 Let's test compliance with the left identity law:
542
543 <pre>
544 # let bind u f (w:s) = f (u w) w;;
545 val bind : (s -> 'a) -> ('a -> s -> 'b) -> s -> 'b = <fun>
546 # bind (unit 'a') unit 1;;
547 - : char = 'a'
548 </pre>
549
550 We'll assume that this and the other laws always hold.
551
552 We now build up some extensional meanings:
553
554         let left w x = match (w,x) with (2,'c') -> false | _ -> true;;
555
556 This function says that everyone always left, except for Cam in world
557 2 (i.e., `left 2 'c' == false`).
558
559 Then the way to evaluate an extensional sentence is to determine the
560 extension of the verb phrase, and then apply that extension to the
561 extension of the subject:
562
563 <pre>
564 let extapp fn arg w = fn w (arg w);;
565
566 extapp left ann 1;;
567 # - : bool = true
568
569 extapp left cam 2;;
570 # - : bool = false
571 </pre>
572
573 `extapp` stands for "extensional function application".
574 So Ann left in world 1, but Cam didn't leave in world 2.
575
576 A transitive predicate:
577
578         let saw w x y = (w < 2) && (y < x);;
579         extapp (extapp saw bill) ann 1;; (* true *)
580         extapp (extapp saw bill) ann 2;; (* false *)
581
582 In world 1, Ann saw Bill and Cam, and Bill saw Cam.  No one saw anyone
583 in world two.
584
585 Good.  Now for intensions:
586
587         let intapp fn arg w = fn w arg;;
588
589 The only difference between intensional application and extensional
590 application is that we don't feed the evaluation world to the argument.
591 (See Montague's rules of (intensional) functional application, T4 -- T10.)
592 In other words, instead of taking an extension as an argument,
593 Montague's predicates take a full-blown intension.  
594
595 But for so-called extensional predicates like "left" and "saw", 
596 the extra power is not used.  We'd like to define intensional versions
597 of these predicates that depend only on their extensional essence.
598 Just as we used bind to define a version of addition that interacted
599 with the option monad, we now use bind to intensionalize an
600 extensional verb:
601
602 <pre>
603 let lift pred w arg = bind arg (fun x w -> pred w x) w;;
604
605 intapp (lift left) ann 1;; (* true: Ann still left in world 1 *)
606 intapp (lift left) cam 2;; (* false: Cam still didn't leave in world 2 *)
607 </pre>
608
609 Because `bind` unwraps the intensionality of the argument, when the
610 lifted "left" receives an individual concept (e.g., `unit 'a'`) as
611 argument, it's the extension of the individual concept (i.e., `'a'`)
612 that gets fed to the basic extensional version of "left".  (For those
613 of you who know Montague's PTQ, this use of bind captures Montague's
614 third meaning postulate.)
615
616 Likewise for extensional transitive predicates like "saw":
617
618 <pre>
619 let lift2 pred w arg1 arg2 = 
620   bind arg1 (fun x -> bind arg2 (fun y w -> pred w x y)) w;;
621 intapp (intapp (lift2 saw) bill) ann 1;;  (* true: Ann saw Bill in world 1 *)
622 intapp (intapp (lift2 saw) bill) ann 2;;  (* false: No one saw anyone in world 2 *)
623 </pre>
624
625 Crucially, an intensional predicate does not use `bind` to consume its
626 arguments.  Attitude verbs like "thought" are intensional with respect
627 to their sentential complement, but extensional with respect to their
628 subject (as Montague noticed, almost all verbs in English are
629 extensional with respect to their subject; a possible exception is "appear"):
630
631 <pre>
632 let think (w:s) (p:s->t) (x:e) = 
633   match (x, p 2) with ('a', false) -> false | _ -> p w;;
634 </pre>
635
636 Ann disbelieves any proposition that is false in world 2.  Apparently,
637 she firmly believes we're in world 2.  Everyone else believes a
638 proposition iff that proposition is true in the world of evaluation.
639
640 <pre>
641 intapp (lift (intapp think
642                      (intapp (lift left)
643                              (unit 'b'))))
644        (unit 'a') 
645 1;; (* true *)
646 </pre>
647
648 So in world 1, Ann thinks that Bill left (because in world 2, Bill did leave).
649
650 The `lift` is there because "think Bill left" is extensional wrt its
651 subject.  The important bit is that "think" takes the intension of
652 "Bill left" as its first argument.
653
654 <pre>
655 intapp (lift (intapp think
656                      (intapp (lift left)
657                              (unit 'c'))))
658        (unit 'a') 
659 1;; (* false *)
660 </pre>
661
662 But even in world 1, Ann doesn't believe that Cam left (even though he
663 did: `intapp (lift left) cam 1 == true`).  Ann's thoughts are hung up
664 on what is happening in world 2, where Cam doesn't leave.
665
666 *Small project*: add intersective ("red") and non-intersective
667  adjectives ("good") to the fragment.  The intersective adjectives
668  will be extensional with respect to the nominal they combine with
669  (using bind), and the non-intersective adjectives will take
670  intensional arguments.
671
672 Finally, note that within an intensional grammar, extensional funtion
673 application is essentially just bind:
674
675 <pre>
676 # let swap f x y = f y x;;
677 # bind cam (swap left) 2;;
678 - : bool = false
679 </pre>