d4b1541b2cd34bb3c48adb2088976ba1ea90cc4e
[lambda.git] / topics / week7_monads.mdwn
1 <!-- λ Λ ∀ ≡ α β γ ρ ω Ω -->
2 <!-- Loved this one: http://www.stephendiehl.com/posts/monads.html -->
3
4 Introducing Monads
5 ==================
6
7 The [[tradition in the functional programming
8 literature|https://wiki.haskell.org/Monad_tutorials_timeline]] is to
9 introduce monads using a metaphor: monads are spacesuits, monads are
10 monsters, monads are burritos. These metaphors can be helpful, and they
11 can be unhelpful. There's a backlash about the metaphors that tells people
12 to instead just look at the formal definition. We'll give that to you below, but it's
13 sometimes sloganized as
14 [A monad is just a monoid in the category of endofunctors, what's the problem?](http://stackoverflow.com/questions/3870088).
15 Without some intuitive guidance, this can also be unhelpful. We'll try to find a good balance. 
16
17 The closest we will come to metaphorical talk is to suggest that
18 monadic types place objects inside of *boxes*, and that monads wrap
19 and unwrap boxes to expose or enclose the objects inside of them. In
20 any case, our emphasis will be on starting with the abstract structure
21 of monads, followed by instances of monads from the philosophical and
22 linguistics literature.
23
24 ## Box types: type expressions with one free type variable
25
26 Recall that we've been using lower-case Greek letters
27 <code>&alpha;, &beta;, &gamma;, ...</code> as type variables. We'll
28 use `P`, `Q`, `R`, and `S` as schematic metavariables over type expressions, that may or may not contain unbound
29 type variables. For instance, we might have
30
31     P_1 ≡ int
32     P_2 ≡ α -> α
33     P_3 ≡ ∀α. α -> α
34     P_4 ≡ ∀α. α -> β 
35
36 etc.
37
38 A *box type* will be a type expression that contains exactly one free
39 type variable. (You could extend this to expressions with more free variables; then you'd have
40 to specify which one of them the box is capturing. But let's keep it simple.) Some examples (using OCaml's type conventions):
41
42     α option
43     α list
44     (α, R) tree    (assuming R contains no free type variables)
45     (α, α) tree
46
47 The idea is that whatever type the free type variable α might be,
48 the boxed type will be a box that "contains" an object of type `α`.
49 For instance, if `α list` is our box type, and `α` is the type
50 `int`, then in this context, `int list` is the type of a boxed integer.
51
52 Warning: although our initial motivating examples are naturally thought of as "containers" (lists, trees, and so on, with `α`s as their "elments"), with later examples we discuss it will less intuitive to describe the box types that way. For example, where `R` is some fixed type, `R -> α` is a box type.
53
54 The *box type* is the type `α list` (or as we might just say, `list`); the *boxed type* is some specific instantiantion of the free type variable `α`. We'll often write boxed types as a box containing the instance of the free
55 type variable. So if our box type is `α list`, and `α` is instantiated with the specific type `int`, we would write:
56
57 <u>int</u>
58
59 for the type of a boxed `int`. (We'll fool with the markup to make this a genuine box later; for now it will just display as underlined.)
60
61
62
63 ## Kleisli arrows
64
65 A lot of what we'll be doing concerns types that are called *Kleisli arrows*. Don't worry about why they're called that, or if you like go read some Category Theory. All we need to know is that these are functions whose type has the form:
66
67 P -> <u>Q</u>
68
69 That is, they are functions from objects of one type `P` to a boxed type `Q`, for some choice of type expressions `P` and `Q`.
70 For instance, the following are Kleisli arrows:
71
72 int -> <u>bool</u>
73
74 int list -> <u>int list</u>
75
76 In the first, `P` has become `int` and `Q` has become `bool`. (The boxed type <u>Q</u> is <u>bool</u>).
77
78 Note that the left-hand schema `P` is permitted to itself be a boxed type. That is, where
79 if `α list` is our box type, we can write the second arrow as
80
81 <u>int</u> -> <u>Q</u>
82
83 We'll need a number of classes of functions to help us maneuver in the
84 presence of box types. We will want to define a different instance of
85 each of these for whichever box type we're dealing with. (This will
86 become clearly shortly.)
87
88 Here are the types of our crucial functions, together with our pronunciation, and some other names the functions go by. (Usually the type doesn't fix their behavior, which will be discussed below.)
89
90 <code>map (/mæp/): (P -> Q) -> <u>P</u> -> <u>Q</u></code>
91
92 <code>map2 (/mæptu/): (P -> Q -> R) -> <u>P</u> -> <u>Q</u> -> <u>R</u></code>
93
94 <code>mid (/εmaidεnt@tI/ aka unit, return, pure): P -> <u>P</u></code>
95
96 <code>m$ or mapply (/εm@plai/): <u>P -> Q</u> -> <u>P</u> -> <u>Q</u></code>
97
98 <code>&lt;=&lt; or mcomp : (Q -> <u>R</u>) -> (P -> <u>Q</u>) -> (P -> <u>R</u>)</code>
99
100 <code>&gt;=&gt; or mpmoc (m-flipcomp): (P -> <u>Q</u>) -> (Q -> <u>R</u>) -> (P -> <u>R</u>)</code>
101
102 <code>&gt;&gt;= or mbind : (<u>Q</u>) -> (Q -> <u>R</u>) -> (<u>R</u>)</code>
103
104 <code>=&lt;&lt;mdnib (or m-flipbind) (<u>Q</u>) -> (Q -> <u>R</u>) -> (<u>R</u>)</code>
105
106 <code>join: <u>2<u>P</u></u> -> <u>P</u></code> 
107
108 The managerie isn't quite as bewildering as you might suppose. Many of these will
109 be interdefinable. For example, here is how `mcomp` and `mbind` are related: <code>k <=< j ≡
110 \a. (j a >>= k)</code>.
111
112 In most cases of interest, instances of these systems of functions will provide
113 certain useful guarantees.
114
115 *   ***Mappable*** (in Haskelese, "Functors") At the most general level, box types are *Mappable*
116 if there is a `map` function defined for that box type with the type given above. This
117 has to obey the following Map Laws:
118
119     LAWS
120
121 *   ***MapNable*** (in Haskelese, "Applicatives") A Mappable box type is *MapNable*
122        if there are in addition `map2`, `mid`, and `mapply`.  (Given either
123        of `map2` and `mapply`, you can define the other, and also `map`.
124        Moreover, with `map2` in hand, `map3`, `map4`, ... `mapN` are easily definable.) These
125 have to obey the following MapN Laws:
126
127
128 * ***Monad*** (or "Composables") A MapNable box type is a *Monad* if there
129        is in addition an associative `mcomp` having `mid` as its left and
130        right identity. That is, the following Monad Laws must hold:
131
132         mcomp (mcomp j k) l (that is, (j <=< k) <=< l) = mcomp j (mcomp k l)
133         mcomp mid k (that is, mid <=< k) = k
134         mcomp k mid (that is, k <=< mid) = k
135
136 If you have any of `mcomp`, `mpmoc`, `mbind`, or `join`, you can use them to define the others.
137 Also, with these functions you can define `m$` and `map2` from *MapNables*. So all you really need
138 are a definition of `mid`, on the one hand, and one of `mcomp`, `mbind`, or `join`, on the other.
139
140 Here are some interdefinitions: TODO. Names in Haskell TODO.
141
142 ## Examples
143
144 To take a trivial (but, as we will see, still useful) example,
145 consider the identity box type Id: `α`. So if `α` is type `bool`,
146 then a boxed `α` is ... a `bool`. In terms of the box analogy, the
147 Identity box type is a completely invisible box. With the following
148 definitions
149
150     mid ≡ \p. p
151     mcomp ≡ \f g x.f (g x)
152
153 Identity is a monad.  Here is a demonstration that the laws hold:
154
155     mcomp mid k == (\fgx.f(gx)) (\p.p) k
156                 ~~> \x.(\p.p)(kx)
157                 ~~> \x.kx
158                 ~~> k
159     mcomp k mid == (\fgx.f(gx)) k (\p.p)
160                 ~~> \x.k((\p.p)x)
161                 ~~> \x.kx
162                 ~~> k
163     mcomp (mcomp j k) l == mcomp ((\fgx.f(gx)) j k) l
164                        ~~> mcomp (\x.j(kx)) l
165                         == (\fgx.f(gx)) (\x.j(kx)) l
166                        ~~> \x.(\x.j(kx))(lx)
167                        ~~> \x.j(k(lx))
168     mcomp j (mcomp k l) == mcomp j ((\fgx.f(gx)) k l)
169                        ~~> mcomp j (\x.k(lx))
170                         == (\fgx.f(gx)) j (\x.k(lx))
171                        ~~> \x.j((\x.k(lx)) x)
172                        ~~> \x.j(k(lx))
173
174 Id is the favorite monad of mimes.
175
176 To take a slightly less trivial (and even more useful) example,
177 consider the box type `α list`, with the following operations:
178
179     mid: α -> [α]
180     mid a = [a]
181  
182     mcomp: (β -> [γ]) -> (α -> [β]) -> (α -> [γ])
183     mcomp f g a = concat (map f (g a))
184                 = foldr (\b -> \gs -> (f b) ++ gs) [] (g a) 
185                 = [c | b <- g a, c <- f b]
186
187 These three definitions of `mcomp` are all equivalent, and it is easy to see that they obey the monad laws (see exercises).
188
189 In words, `mcomp f g a` feeds the `a` (which has type `α`) to `g`, which returns a list of `β`s;
190 each `β` in that list is fed to `f`, which returns a list of `γ`s. The
191 final result is the concatenation of those lists of `γ`s.
192
193 For example: 
194
195     let f b = [b, b+1] in
196     let g a = [a*a, a+a] in
197     mcomp f g 7 ==> [49, 50, 14, 15]
198
199 `g 7` produced `[49, 14]`, which after being fed through `f` gave us `[49, 50, 14, 15]`.
200
201 Contrast that to `m$` (`mapply`, which operates not on two *box-producing functions*, but instead on two *values of a boxed type*, one containing functions to be applied to the values in the other box, via some predefined scheme. Thus:
202
203     let gs = [(\a->a*a),(\a->a+a)] in
204     let xs = [7, 5] in
205     mapply gs xs ==> [49, 25, 14, 10]
206
207
208 As we illustrated in class, there are clear patterns shared between lists and option types and trees, so perhaps you can see why people want to identify the general structures. But it probably isn't obvious yet why it would be useful to do so. To a large extent, this will only emerge over the next few classes. But we'll begin to demonstrate the usefulness of these patterns by talking through a simple example, that uses the Monadic functions of the Option/Maybe box type.
209
210
211 Safe division
212 -------------
213
214 Integer division presupposes that its second argument
215 (the divisor) is not zero, upon pain of presupposition failure.
216 Here's what my OCaml interpreter says:
217
218     # 12/0;;
219     Exception: Division_by_zero.
220
221 Say we want to explicitly allow for the possibility that
222 division will return something other than a number.
223 To do that, we'll use OCaml's `option` type, which works like this:
224
225     # type 'a option = None | Some of 'a;;
226     # None;;
227     - : 'a option = None
228     # Some 3;;
229     - : int option = Some 3
230
231 So if a division is normal, we return some number, but if the divisor is
232 zero, we return `None`. As a mnemonic aid, we'll prepend a `safe_` to the start of our new divide function.
233
234 <pre>
235 let safe_div (x:int) (y:int) =
236   match y with
237     | 0 -> None
238     | _ -> Some (x / y);;
239
240 (*
241 val safe_div : int -> int -> int option = fun
242 # safe_div 12 2;;
243 - : int option = Some 6
244 # safe_div 12 0;;
245 - : int option = None
246 # safe_div (safe_div 12 2) 3;;
247 # safe_div (safe_div 12 2) 3;;
248             ~~~~~~~~~~~~~
249 Error: This expression has type int option
250        but an expression was expected of type int
251 *)
252 </pre>
253
254 This starts off well: dividing 12 by 2, no problem; dividing 12 by 0,
255 just the behavior we were hoping for. But we want to be able to use
256 the output of the safe-division function as input for further division
257 operations. So we have to jack up the types of the inputs:
258
259 <pre>
260 let safe_div2 (u:int option) (v:int option) =
261   match u with
262           None -> None
263         | Some x -> (match v with
264                                   Some 0 -> None
265                                 | Some y -> Some (x / y));;
266
267 (*
268 val safe_div2 : int option -> int option -> int option = <fun>
269 # safe_div2 (Some 12) (Some 2);;
270 - : int option = Some 6
271 # safe_div2 (Some 12) (Some 0);;
272 - : int option = None
273 # safe_div2 (safe_div2 (Some 12) (Some 0)) (Some 3);;
274 - : int option = None
275 *)
276 </pre>
277
278 Beautiful, just what we need: now we can try to divide by anything we
279 want, without fear that we're going to trigger any system errors.
280
281 I prefer to line up the `match` alternatives by using OCaml's
282 built-in tuple type:
283
284 <pre>
285 let safe_div2 (u:int option) (v:int option) =
286   match (u, v) with
287     | (None, _) -> None
288     | (_, None) -> None
289     | (_, Some 0) -> None
290     | (Some x, Some y) -> Some (x / y);;
291 </pre>
292
293 So far so good. But what if we want to combine division with
294 other arithmetic operations? We need to make those other operations
295 aware of the possibility that one of their arguments has triggered a
296 presupposition failure:
297
298 <pre>
299 let safe_add (u:int option) (v:int option) =
300   match (u, v) with
301     | (None, _) -> None
302     | (_, None) -> None
303     | (Some x, Some y) -> Some (x + y);;
304
305 (*
306 val safe_add : int option -> int option -> int option = <fun>
307 # safe_add (Some 12) (Some 4);;
308 - : int option = Some 16
309 # safe_add (safe_div (Some 12) (Some 0)) (Some 4);;
310 - : int option = None
311 *)
312 </pre>
313
314 This works, but is somewhat disappointing: the `safe_add` operation
315 doesn't trigger any presupposition of its own, so it is a shame that
316 it needs to be adjusted because someone else might make trouble.
317
318 But we can automate the adjustment. The standard way in OCaml,
319 Haskell, and other functional programming languages, is to use the monadic
320 `bind` operator, `>>=`. (The name "bind" is not well chosen from our
321 perspective, but this is too deeply entrenched by now.) As mentioned above,
322 there needs to be a different `>>=` operator for each Monad or box type you're working with.
323 Haskell finesses this by "overloading" the single symbol `>>=`; you can just input that
324 symbol and it will calculate from the context of the surrounding type constraints what
325 monad you must have meant. In OCaml, the `>>=` or `bind` operator is not pre-defined, but we will
326 give you a library that has definitions for all the standard monads, as in Haskell.
327 For now, though, we will define our `bind` operation by hand:
328
329 <pre>
330 let bind (u: int option) (f: int -> (int option)) =
331   match u with
332     |  None -> None
333     | Some x -> f x;;
334
335 let safe_add3 (u: int option) (v: int option) =
336   bind u (fun x -> bind v (fun y -> Some (x + y)));;
337
338 (* This is really just `map2 (+)`, using the `map2` operation that corresponds to
339    definition of `bind`. *)
340
341 let safe_div3 (u: int option) (v: int option) =
342   bind u (fun x -> bind v (fun y -> if 0 = y then None else Some (x / y)));;
343
344 (* This goes back to some of the simplicity of the original safe_div, without the complexity
345    introduced by safe_div2. *)
346 </pre>
347
348 The above definitions look even simpler if you focus on the fact that `safe_add3` can be written as simply `map2 (+)`, and that `safe_div3` could be written as `u >>= fun x -> v >>= fun y -> if 0 = y then None else Some (x / y)`. Haskell has an even more user-friendly notation for this, namely:
349
350     safe_div3 :: Maybe Int -> Maybe Int -> Maybe Int
351     safe_div3 u v = do {x <- u;
352                         y <- v;
353                         if 0 == y then Nothing else return (x `div` y)}
354
355 Let's see our new functions in action:
356
357 (*
358 # safe_div3 (safe_div3 (Some 12) (Some 2)) (Some 3);;
359 - : int option = Some 2
360 #  safe_div3 (safe_div3 (Some 12) (Some 0)) (Some 3);;
361 - : int option = None
362 # safe_add3 (safe_div3 (Some 12) (Some 0)) (Some 3);;
363 - : int option = None
364 *)
365 </pre>
366
367 Compare the new definitions of `safe_add3` and `safe_div3` closely: the definition
368 for `safe_add3` shows what it looks like to equip an ordinary operation to
369 survive in dangerous presupposition-filled world. Note that the new
370 definition of `safe_add3` does not need to test whether its arguments are
371 None objects or real numbers---those details are hidden inside of the
372 `bind` function.
373
374 The definition of `safe_div3` shows exactly what extra needs to be said in
375 order to trigger the no-division-by-zero presupposition. Here, too, we don't
376 need to keep track of what presuppositions may have already failed
377 for whatever reason on our inputs.
378
379 (Linguitics note: Dividing by zero is supposed to feel like a kind of
380 presupposition failure. If we wanted to adapt this approach to
381 building a simple account of presupposition projection, we would have
382 to do several things. First, we would have to make use of the
383 polymorphism of the `option` type. In the arithmetic example, we only
384 made use of `int option`s, but when we're composing natural language
385 expression meanings, we'll need to use types like `N option`, `Det option`,
386 `VP option`, and so on. But that works automatically, because we can use
387 any type for the `'a` in `'a option`. Ultimately, we'd want to have a
388 theory of accommodation, and a theory of the situations in which
389 material within the sentence can satisfy presuppositions for other
390 material that otherwise would trigger a presupposition violation; but,
391 not surprisingly, these refinements will require some more
392 sophisticated techniques than the super-simple Option monad.)
393