6dfbdeb8fbe803e2a32ebb6547fbe5e5a7ee7c84
[lambda.git] / topics / _week8_monads_in_general.mdwn
1 Monads in General
2 -----------------
3
4 We've just seen a way to separate thinking about error conditions
5 (such as trying to divide by zero) from thinking about normal
6 arithmetic computations.  We did this by making use of the `option`
7 type: in each place where we had something of type `int`, we put
8 instead something of type `int option`, which is a sum type consisting
9 either of one choice with an `int` payload, or else a `None` choice
10 which we interpret as signaling that something has gone wrong.
11
12 The goal was to make normal computing as convenient as possible: when
13 we're adding or multiplying, we don't have to worry about generating
14 any new errors, so we would rather not think about the difference
15 between `int`s and `int option`s.  We tried to accomplish this by
16 defining a `bind` operator, which enabled us to peel away the `option`
17 husk to get at the delicious integer inside.  There was also a
18 homework problem which made this even more convenient by defining a
19 `lift` operator that mapped any binary operation on plain integers
20 into a lifted operation that understands how to deal with `int
21 option`s in a sensible way.
22
23 So what exactly is a monad?  We can consider a monad to be a system
24 that provides at least the following three elements:
25
26 *       A complex type that's built around some more basic type. Usually
27         the complex type will be polymorphic, and so can apply to different basic types.
28         In our division example, the polymorphism of the `'a option` type
29         provides a way of building an option out of any other type of object.
30         People often use a container metaphor: if `u` has type `int option`,
31         then `u` is a box that (may) contain an integer.
32
33                 type 'a option = None | Some of 'a;;
34
35 *       A way to turn an ordinary value into a monadic value.  In OCaml, we
36         did this for any integer `x` by mapping it to
37         the option `Some x`.  In the general case, this operation is
38         known as `unit` or `return.` Both of those names are terrible. This
39         operation is only very loosely connected to the `unit` type we were
40         discussing earlier (whose value is written `()`). It's also only
41         very loosely connected to the "return" keyword in many other
42         programming languages like C. But these are the names that the literature
43         uses.  [The rationale for "unit" comes from the monad laws
44         (see below), where the unit function serves as an identity,
45         just like the unit number (i.e., 1) serves as the identity
46         object for multiplication.  The rationale for "return" comes
47         from a misguided desire to resonate with C programmers and
48         other imperative types.]
49
50         The unit/return operation is a way of lifting an ordinary object into
51         the monadic box you've defined, in the simplest way possible. You can think
52         of the singleton function as an example: it takes an ordinary object
53         and returns a set containing that object. In the example we've been
54         considering:
55
56                 let unit x = Some x;;
57                 val unit : 'a -> 'a option = <fun>
58
59         So `unit` is a way to put something inside of a monadic box. It's crucial
60         to the usefulness of monads that there will be monadic boxes that
61         aren't the result of that operation. In the Option/Maybe monad, for
62         instance, there's also the empty box `None`. In another (whimsical)
63         example, you might have, in addition to boxes merely containing integers,
64         special boxes that contain integers and also sing a song when they're opened. 
65
66         The unit/return operation will always be the simplest, conceptually
67         most straightforward way to lift an ordinary value into a monadic value
68         of the monadic type in question.
69
70 *       Thirdly, an operation that's often called `bind`. As we said before, this is another
71         unfortunate name: this operation is only very loosely connected to
72         what linguists usually mean by "binding." In our Option/Maybe monad, the
73         bind operation is:
74
75                 let bind u f = match u with None -> None | Some x -> f x;;
76                 val bind : 'a option -> ('a -> 'b option) -> 'b option = <fun>
77
78         Note the type: `bind` takes two arguments: first, a monadic box
79         (in this case, an `'a option`); and second, a function from
80         ordinary objects to monadic boxes. `bind` then returns a monadic
81         value: in this case, a `'b option` (you can start with, e.g., `int option`s
82         and end with `bool option`s).
83
84         Intuitively, the interpretation of what `bind` does is this:
85         the first argument is a monadic value `u`, which 
86         evaluates to a box that (maybe) contains some ordinary value, call it `x`.
87         Then the second argument uses `x` to compute a new monadic
88         value.  Conceptually, then, we have
89
90                 let bind u f = (let x = unbox u in f x);;
91
92         The guts of the definition of the `bind` operation amount to
93         specifying how to unbox the monadic value `u`.  In the `bind`
94         operator for the Option monad, we unboxed the monadic value by
95         matching it with the pattern `Some x`---whenever `u`
96         happened to be a box containing an integer `x`, this allowed us to
97         get our hands on that `x` and feed it to `f`.
98
99         If the monadic box didn't contain any ordinary value,
100         we instead pass through the empty box unaltered.
101
102         In a more complicated case, like our whimsical "singing box" example
103         from before, if the monadic value happened to be a singing box
104         containing an integer `x`, then the `bind` operation would probably
105         be defined so as to make sure that the result of `f x` was also
106         a singing box. If `f` also wanted to insert a song, you'd have to decide
107         whether both songs would be carried through, or only one of them.
108         (Are you beginning to realize how wierd and wonderful monads
109         can be?)
110
111         There is no single `bind` function that dictates how this must go.
112         For each new monadic type, this has to be worked out in an
113         useful way.
114
115 So the "Option/Maybe monad" consists of the polymorphic `option` type, the
116 `unit`/return function, and the `bind` function.
117
118
119 A note on notation: Haskell uses the infix operator `>>=` to stand for
120 `bind`: wherever you see `u >>= f`, that means `bind u f`.
121 Wadler uses &#8902;, but that hasn't been widely adopted (unfortunately).
122
123 Also, if you ever see this notation:
124
125         do
126                 x <- u
127                 f x
128
129 That's a Haskell shorthand for `u >>= (\x -> f x)`, that is, `bind u f`.
130 Similarly:
131
132         do
133                 x <- u
134                 y <- v
135                 f x y
136
137 is shorthand for `u >>= (\x -> v >>= (\y -> f x y))`, that is, `bind u
138 (fun x -> bind v (fun y -> f x y))`. Those who did last week's
139 homework may recognize this last expression.  You can think of the
140 notation like this: take the singing box `u` and evaluate it (which
141 includes listening to the song).  Take the int contained in the
142 singing box (the end result of evaluting `u`) and bind the variable
143 `x` to that int.  So `x <- u` means "Sing me up an int, which I'll call
144 `x`".
145
146 (Note that the above "do" notation comes from Haskell. We're mentioning it here
147 because you're likely to see it when reading about monads. (See our page on [[Translating between OCaml Scheme and Haskell]].) It won't work in
148 OCaml. In fact, the `<-` symbol already means something different in OCaml,
149 having to do with mutable record fields. We'll be discussing mutation someday
150 soon.)
151
152 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:
153
154         # type 'a list
155
156 The `unit`/return operation is:
157
158         # let unit x = [x];;
159         val unit : 'a -> 'a list = <fun>
160
161 That is, the simplest way to lift an `'a` into an `'a list` is just to make a
162 singleton list of that `'a`. Finally, the `bind` operation is:
163
164         # let bind u f = List.concat (List.map f u);;
165         val bind : 'a list -> ('a -> 'b list) -> 'b list = <fun>
166         
167 What's going on here? Well, consider `List.map f u` first. This goes through all
168 the members of the list `u`. There may be just a single member, if `u = unit x`
169 for some `x`. Or on the other hand, there may be no members, or many members. In
170 any case, we go through them in turn and feed them to `f`. Anything that gets fed
171 to `f` will be an `'a`. `f` takes those values, and for each one, returns a `'b list`.
172 For example, it might return a list of all that value's divisors. Then we'll
173 have a bunch of `'b list`s. The surrounding `List.concat ( )` converts that bunch
174 of `'b list`s into a single `'b list`:
175
176         # List.concat [[1]; [1;2]; [1;3]; [1;2;4]]
177         - : int list = [1; 1; 2; 1; 3; 1; 2; 4]
178
179 So now we've seen two monads: the Option/Maybe monad, and the List monad. For any
180 monadic system, there has to be a specification of the complex monad type,
181 which will be parameterized on some simpler type `'a`, and the `unit`/return
182 operation, and the `bind` operation. These will be different for different
183 monadic systems.
184
185 Many monadic systems will also define special-purpose operations that only make
186 sense for that system.
187
188 Although the `unit` and `bind` operation are defined differently for different
189 monadic systems, there are some general rules they always have to follow.
190
191
192 The Monad Laws
193 --------------
194
195 Just like good robots, monads must obey three laws designed to prevent
196 them from hurting the people that use them or themselves.
197
198 *       **Left identity: unit is a left identity for the bind operation.**
199         That is, for all `f:'a -> 'b m`, where `'b m` is a monadic
200         type, we have `(unit x) >>= f == f x`.  For instance, `unit` is itself
201         a function of type `'a -> 'a m`, so we can use it for `f`:
202
203                 # let unit x = Some x;;
204                 val unit : 'a -> 'a option = <fun>
205                 # let ( >>= ) u f = match u with None -> None | Some x -> f x;;
206                 val ( >>= ) : 'a option -> ('a -> 'b option) -> 'b option = <fun>
207
208         The parentheses is the magic for telling OCaml that the
209         function to be defined (in this case, the name of the function
210         is `>>=`, pronounced "bind") is an infix operator, so we write
211         `u >>= f` or equivalently `( >>= ) u f` instead of `>>= u
212         f`.
213
214                 # unit 2;;
215                 - : int option = Some 2
216                 # unit 2 >>= unit;;
217                 - : int option = Some 2
218
219         Now, for a less trivial instance of a function from `int`s to `int option`s:
220
221                 # let divide x y = if 0 = y then None else Some (x/y);;
222                 val divide : int -> int -> int option = <fun>
223                 # divide 6 2;;
224                 - : int option = Some 3
225                 # unit 2 >>= divide 6;;
226                 - : int option = Some 3
227
228                 # divide 6 0;;
229                 - : int option = None
230                 # unit 0 >>= divide 6;;
231                 - : int option = None
232
233
234 *       **Associativity: bind obeys a kind of associativity**. Like this:
235
236                 (u >>= f) >>= g  ==  u >>= (fun x -> f x >>= g)
237
238         If you don't understand why the lambda form is necessary (the
239         "fun x -> ..." part), you need to look again at the type of `bind`.
240
241         Wadler and others try to make this look nicer by phrasing it like this,
242         where U, V, and W are schematic for any expressions with the relevant monadic type:
243
244                 (U >>= fun x -> V) >>= fun y -> W  ==  U >>= fun x -> (V >>= fun y -> W)
245
246         Some examples of associativity in the Option monad (bear in
247         mind that in the Ocaml implementation of integer division, 2/3
248         evaluates to zero, throwing away the remainder):
249
250                 # Some 3 >>= unit >>= unit;; 
251                 - : int option = Some 3
252                 # Some 3 >>= (fun x -> unit x >>= unit);;
253                 - : int option = Some 3
254
255                 # Some 3 >>= divide 6 >>= divide 2;;
256                 - : int option = Some 1
257                 # Some 3 >>= (fun x -> divide 6 x >>= divide 2);;
258                 - : int option = Some 1
259
260                 # Some 3 >>= divide 2 >>= divide 6;;
261                 - : int option = None
262                 # Some 3 >>= (fun x -> divide 2 x >>= divide 6);;
263                 - : int option = None
264
265         Of course, associativity must hold for *arbitrary* functions of
266         type `'a -> 'b m`, where `m` is the monad type.  It's easy to
267         convince yourself that the `bind` operation for the Option monad
268         obeys associativity by dividing the inputs into cases: if `u`
269         matches `None`, both computations will result in `None`; if
270         `u` matches `Some x`, and `f x` evalutes to `None`, then both
271         computations will again result in `None`; and if the value of
272         `f x` matches `Some y`, then both computations will evaluate
273         to `g y`.
274
275 *       **Right identity: unit is a right identity for bind.**  That is, 
276         `u >>= unit == u` for all monad objects `u`.  For instance,
277
278                 # Some 3 >>= unit;;
279                 - : int option = Some 3
280                 # None >>= unit;;
281                 - : 'a option = None
282
283
284 More details about monads
285 -------------------------
286
287 If you studied algebra, you'll remember that a *monoid* is an
288 associative operation with a left and right identity.  For instance,
289 the natural numbers along with multiplication form a monoid with 1
290 serving as the left and right identity.  That is, `1 * u == u == u * 1` for all
291 `u`, and `(u * v) * w == u * (v * w)` for all `u`, `v`, and `w`.  As
292 presented here, a monad is not exactly a monoid, because (unlike the
293 arguments of a monoid operation) the two arguments of the bind are of
294 different types.  But it's possible to make the connection between
295 monads and monoids much closer. This is discussed in [Monads in Category
296 Theory](/advanced_topics/monads_in_category_theory).
297
298 See also:
299
300 *       [Haskell wikibook on Monad Laws](http://www.haskell.org/haskellwiki/Monad_Laws).
301 *       [Yet Another Haskell Tutorial on Monad Laws](http://en.wikibooks.org/wiki/Haskell/YAHT/Monads#Definition)
302 *       [Haskell wikibook on Understanding Monads](http://en.wikibooks.org/wiki/Haskell/Understanding_monads)
303 *       [Haskell wikibook on Advanced Monads](http://en.wikibooks.org/wiki/Haskell/Advanced_monads)
304 *       [Haskell wikibook on do-notation](http://en.wikibooks.org/wiki/Haskell/do_Notation)
305 *       [Yet Another Haskell Tutorial on do-notation](http://en.wikibooks.org/wiki/Haskell/YAHT/Monads#Do_Notation)
306
307
308 Here are some papers that introduced monads into functional programming:
309
310 *       [Eugenio Moggi, Notions of Computation and Monads](http://www.disi.unige.it/person/MoggiE/ftp/ic91.pdf): Information and Computation 93 (1) 1991. Would be very difficult reading for members of this seminar. However, the following two papers should be accessible.
311
312 *       [Philip Wadler. The essence of functional programming](http://homepages.inf.ed.ac.uk/wadler/papers/essence/essence.ps):
313 invited talk, *19'th Symposium on Principles of Programming Languages*, ACM Press, Albuquerque, January 1992.
314 <!--    This paper explores the use monads to structure functional programs. No prior knowledge of monads or category theory is required.
315         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.
316         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.-->
317
318 *       [Philip Wadler. Monads for Functional Programming](http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf):
319 in M. Broy, editor, *Marktoberdorf Summer School on Program Design
320 Calculi*, Springer Verlag, NATO ASI Series F: Computer and systems
321 sciences, Volume 118, August 1992. Also in J. Jeuring and E. Meijer,
322 editors, *Advanced Functional Programming*, Springer Verlag, 
323 LNCS 925, 1995. Some errata fixed August 2001.
324 <!--    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.-->
325
326
327 There's a long list of monad tutorials on the [[Offsite Reading]] page. (Skimming the titles is somewhat amusing.) If you are confused by monads, make use of these resources. Read around until you find a tutorial pitched at a level that's helpful for you.
328
329 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
330 Theory](/advanced_topics/monads_in_category_theory) notes do so, for example.
331
332 Here are some of the other general monad operations. 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 `lift2 (+)` 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 the 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 specific `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 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
376 two computations to give the same result:
377
378         List.map (fun x -> f (g x)) lst
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) u = u
389         ap (ap (ap (unit compose) u) v) w = ap u (ap v w)
390         ap (unit f) (unit x) = unit (f x)
391         ap u (unit x) = ap (unit (fun f -> f x)) 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 u = u >>= compose unit f
407         lift f u = ap (unit f) u
408         lift2 f u v = u >>= (fun x -> v >>= (fun y -> unit (f x y)))
409         lift2 f u v = ap (lift f u) v = ap (ap (unit f) u) v
410         ap u v = u >>= (fun f -> lift f v)
411         ap u v = lift2 id u v
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.  One major 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 But first, we'll look at several linguistic applications for monads, based
429 on what's called the *Reader monad*.
430
431 ##[[Reader Monad for Variable Binding]]##
432
433 ##[[Reader Monad for Intensionality]]##
434