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