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