tweaks
[lambda.git] / topics / week7_introducing_monads.mdwn
index c7f658d..b32b9cf 100644 (file)
@@ -1,8 +1,6 @@
 <!-- λ Λ ∀ ≡ α β γ ρ ω Ω ○ μ η δ ζ ξ ⋆ ★ • ∙ ● 𝟎 𝟏 𝟐 𝟘 𝟙 𝟚 𝟬 𝟭 𝟮 -->
 <!-- Loved this one: http://www.stephendiehl.com/posts/monads.html -->
 
-Introducing Monads
-==================
 
 The [[tradition in the functional programming
 literature|https://wiki.haskell.org/Monad_tutorials_timeline]] is to
@@ -22,11 +20,10 @@ any case, our emphasis will be on starting with the abstract structure
 of monads, followed in coming weeks by instances of monads from the philosophical and
 linguistics literature.
 
-> <small>After you've read this once and are coming back to re-read it to try to digest the details further, the "endofunctors" that slogan is talking about are a combination of our boxes and their associated maps. Their "monoidal" character is captured in the Monad Laws, where a "monoid"---don't confuse with a mon*ad*---is a simpler algebraic notion, meaning a universe with some associative operation that has an identity. For advanced study, here are some further links on the relation between monads as we're working with them and monads as they appear in Category Theory:
-[1](http://en.wikipedia.org/wiki/Outline_of_category_theory)
-[2](http://lambda1.jimpryor.net/advanced_topics/monads_in_category_theory/)
-[3](http://en.wikibooks.org/wiki/Haskell/Category_theory)
-[4](https://wiki.haskell.org/Category_theory), where you should follow the further links discussing Functors, Natural Transformations, and Monads.</small>
+> <small>After you've read this once and are coming back to re-read it to try to digest the details further, the "endofunctors" that slogan is talking about are a combination of our boxes and their associated `map`s. Their "monoidal" character is captured in the Monad Laws, for which see below.</small>
+
+[[!toc levels=2]]
+
 
 
 ## Box types: type expressions with one free type variable ##
@@ -128,7 +125,7 @@ Here are the types of our crucial functions, together with our pronunciation, an
 
 <code>m$ or mapply (/εm@plai/): <u>P -> Q</u> -> <u>P</u> -> <u>Q</u></code>
 
-> We'll use `m$` as a left-associative infix operator, reminiscent of (the right-associative) `$` which is just ordinary function application (also expressed by mere left-associative juxtaposition). In the class presentation Jim called `m$` `â\97\8f`. In Haskell, it's called `Control.Monad.ap` or `Control.Applicative.<*>`.
+> We'll use `m$` as a left-associative infix operator, reminiscent of (the right-associative) `$` which is just ordinary function application (also expressed by mere left-associative juxtaposition). In the class presentation Jim called `m$` `â\9a«`. In Haskell, it's called `Control.Monad.ap` or `Control.Applicative.<*>`.
 
 <code>&lt;=&lt; or mcomp : (Q -> <u>R</u>) -> (P -> <u>Q</u>) -> (P -> <u>R</u>)</code>
 
@@ -212,15 +209,20 @@ has to obey the following Map Laws:
         k >=> mid == k
         mid >=> k == k
 
-    If you have any of `mcomp`, `mpmoc`, `mbind`, or `join`, you can use them to define the others. Also, with these functions you can define `m$` and `map2` from *MapNables*. So with Monads, all you really need to get the whole system of functions are a definition of `mid`, on the one hand, and one of `mcomp`, `mbind`, or `join`, on the other.
+    If you studied algebra, you'll remember that a mon*oid* is a universe with some associative operation that has an identity. For example, the natural numbers form a monoid with multiplication as the operation and `1` as the identity, or with addition as the operation and `0` as the identity. Strings form a monoid with concatenation as the operation and the empty string as the identity. (This example shows that the operation need not be commutative.) Monads are a kind of generalization of this notion, and that's why they're named as they are. The key difference is that for monads, the values being operated on need not be of the same type. They *can* be, if they're all Kleisli arrows of a single type <code>P -> <u>P</u></code>. But they needn't be. Their types only need to "cohere" in certain ways.
 
-    In practice, you will often work with `>>=`. In the Haskell manuals, they express the Monad Laws using `>>=` instead of the composition operators. This looks similar, but doesn't have the same symmetry:
+    In the Haskell manuals, they express the Monad Laws using `>>=` instead of the composition operators `>=>` or `<=<`. This looks similar, but doesn't have the same symmetry:
 
         u >>= (\a -> k a >>= j) == (u >>= k) >>= j
         u >>= mid == u
         mid a >>= k == k a
 
-     Also, Haskell calls `mid` `return` or `pure`, but we've stuck to our terminology in this context.
+    (Also, Haskell calls `mid` `return` or `pure`, but we've stuck to our terminology in this context.) Some authors try to make the first of those Laws look more symmetrical by writing it as:
+
+        (A >>= \a -> B) >>= \b -> C == A >>= (\a -> B >>= \b -> C)
+
+    If you have any of `mcomp`, `mpmoc`, `mbind`, or `join`, you can use them to define the others. Also, with these functions you can define `m$` and `map2` from *MapNables*. So with Monads, all you really need to get the whole system of functions are a definition of `mid`, on the one hand, and one of `mcomp`, `mbind`, or `join`, on the other.
+
 
     > <small>In Category Theory discussion, the Monad Laws are instead expressed in terms of `join` (which they call `μ`) and `mid` (which they call `η`). These are assumed to be "natural transformations" for their box type, which means that they satisfy these equations with that box type's `map`:
     > <pre>map f ○ mid == mid ○ f<br>map f ○ join == join ○ map (map f)</pre>
@@ -228,9 +230,11 @@ has to obey the following Map Laws:
     > <pre>join ○ (map join) == join ○ join<br>join ○ mid == id == join ○ map mid</pre>
     > The first of these says that if you have a triply-boxed type, and you first merge the inner two boxes (with `map join`), and then merge the resulting box with the outermost box, that's the same as if you had first merged the outer two boxes, and then merged the resulting box with the innermost box. The second law says that if you take a box type and wrap a second box around it (with `mid`) and then merge them, that's the same as if you had done nothing, or if you had instead wrapped a second box around each element of the original (with `map mid`, leaving the original box on the outside), and then merged them.<p>
     > The Category Theorist would state these Laws like this, where `M` is the endofunctor that takes us from type `α` to type <code><u>α</u></code>:
-    > <pre>μ ○ M(μ) == μ ○ μ<br>μ ○ η == id == μ ○ M(η)</pre></small>
+    > <pre>μ ○ M(μ) == μ ○ μ<br>μ ○ η == id == μ ○ M(η)</pre>
     > A word of advice: if you're doing any work in this conceptual neighborhood and need a Greek letter, don't use μ. In addition to the preceding usage, there's also a use in recursion theory (for the minimization operator), in type theory (as a fixed point operator for types), and in the λμ-calculus, which is a formal system that deals with _continuations_, which we will focus on later in the course. So μ already exhibits more ambiguity than it can handle.
+    > We link to further reading about the Category Theory origins of Monads below.</small>
 
+There isn't any single `mid` function, or single `mbind` function, and so on. For each new box type, this has to be worked out in a useful way. And as we hinted, in many cases the choice of box *type* still leaves some latitude about how they should be defined. We commonly talk about "the List Monad" to mean a combination of the choice of `α list` for the box type and particular definitions for the various functions listed above. There's also "the ZipList MapNable/Applicative" which combines that same box type with other choices for (some of) the functions. Many of these packages also define special-purpose operations that only make sense for that system, but not for other Monads or Mappables.
 
 As hinted in last week's homework and explained in class, the operations available in a Mappable system exactly preserve the "structure" of the boxed type they're operating on, and moreover are only sensitive to what content is in the corresponding original position. If you say `map f [1,2,3]`, then what ends up in the first position of the result depends only on how `f` and `1` combine.
 
@@ -241,7 +245,7 @@ With `map`, you can supply an `f` such that `map f [3,2,0,1] == [[3,3,3],[2,2],[
 For Monads (Composables), on the other hand, you can perform more radical transformations of that sort. For example, `join (map (\x. dup x x) [3,2,0,1])` would give us `[3,3,3,2,2,1]` (for a suitable definition of `dup`).
 
 <!--
-Some global transformations that we work with in semantics, like Veltman's test functions, can't directly be expressed in terms of the  primitive Monad operations? For example, there's no `j` such that `xs >>= j == mzero` if `xs` anywhere contains the value `1`.
+Some global transformations that we work with in semantics, like Veltman's test functions, can't directly be expressed in terms of the general Monad operations. For example, there's no `j` such that `xs >>= j == mzero` if `xs` anywhere contains the value `1`. That would instead be defined as a special-purpose operation, specific to some restricted class of Monads.
 -->
 
 
@@ -283,7 +287,7 @@ Here are some other monadic notion that you may sometimes encounter:
 
 * Haskell has a notion `>>` definable as `\u v. map (const id) u m$ v`, or as `\u v. u >>= const v`. This is often useful, and `u >> v` won't in general be identical to just `v`. For example, using the box type `List α`, `[1,2,3] >> [4,5] == [4,5,4,5,4,5]`. But in the special case of `mzero`, it is a consequence of what we said above that `anything >> mzero == mzero`. Haskell also calls `>>` `Control.Applicative.*>`.
 
-* Haskell has a correlative notion `Control.Applicative.<*`, definable as `\u v. map const u m$ v`. For example, `[1,2,3] <* [4,5] == [1,1,2,2,3,3]`. You might expect Haskell to call `<*` `<<`, but they don't. They used to use `<<` for `flip (>>)` instead, but now they seem not to use `<<` anymore.
+* Haskell has a correlative notion `Control.Applicative.<*`, definable as `\u v. map const u m$ v`. For example, `[1,2,3] <* [4,5] == [1,1,2,2,3,3]`. <!-- You might expect Haskell to call `<*` `<<`, but they don't. I thought they used to use `<<` for `flip (>>)` instead, but now I can't confirm that this was ever the case. -->
 
 * <code>mapconst</code> is definable as `map ○ const`. For example `mapconst 4 [1,2,3] == [4,4,4]`. Haskell calls `mapconst` `<$` in `Data.Functor` and `Control.Applicative`. They also use `$>` for `flip mapconst`, and `Control.Monad.void` for `mapconst ()`.
 
@@ -377,3 +381,40 @@ But for some types neither of these will be the case. For function types, as we
 
 For the third failure, that is examples of MapNables that aren't Monads, we'll just state that lists where the `map2` operation is taken to be zipping rather than taking the Cartesian product (what in Haskell are called `ZipList`s), these are claimed to exemplify that failure. But we aren't now in a position to demonstrate that to you.
 
+
+## Further Reading ##
+
+As we mentioned above, the notions of Monads have their origin in Category Theory, where they are mostly specified in terms of (what we call) `mid` and `join`. For advanced study, here are some further links on the relation between monads as we're working with them and monads as they appear in Category Theory:
+[1](http://en.wikipedia.org/wiki/Outline_of_category_theory)
+[2](http://lambda1.jimpryor.net/advanced_topics/monads_in_category_theory/)
+[3](http://en.wikibooks.org/wiki/Haskell/Category_theory)
+[4](https://wiki.haskell.org/Category_theory), where you should follow the further links discussing Functors, Natural Transformations, and Monads.
+
+Here are some papers that introduced Monads into functional programming:
+
+*      Eugenio Moggi, Notions of Computation and Monads: Information and Computation 93 (1) 1991. This paper is available online, but would be very difficult reading for members of this seminar, so we won't link to it. <!-- http://www.disi.unige.it/person/MoggiE/ftp/ic91.pdf --> However, the next two papers should be accessible.
+
+*      [Philip Wadler. The essence of functional programming](http://homepages.inf.ed.ac.uk/wadler/papers/essence/essence.ps):
+invited talk, *19'th Symposium on Principles of Programming Languages*, ACM Press, Albuquerque, January 1992.
+<!--   This paper explores the use monads to structure functional programs. No prior knowledge of monads or category theory is required.
+       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.
+       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. -->
+
+*      [Philip Wadler. Monads for Functional Programming](http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf):
+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.
+<!--    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. -->
+
+Here is some other reading:
+
+*      [Haskell wiki on Monad Laws](http://www.haskell.org/haskellwiki/Monad_Laws)
+*      [Yet Another Haskell Tutorial on Monad Laws](http://en.wikibooks.org/wiki/Haskell/YAHT/Monads#Definition)
+*      [Haskell wikibook on Understanding Monads](http://en.wikibooks.org/wiki/Haskell/Understanding_monads)
+*      [Haskell wikibook on Advanced Monads](http://en.wikibooks.org/wiki/Haskell/Advanced_monads)
+*      [Haskell wikibook on do-notation](http://en.wikibooks.org/wiki/Haskell/do_Notation)
+*      [Yet Another Haskell Tutorial on do-notation](http://en.wikibooks.org/wiki/Haskell/YAHT/Monads#Do_Notation)
+
+There's a long list of monad tutorials linked at the [[Haskell wiki|https://wiki.haskell.org/Monad_tutorials_timeline]] (we linked to this at the top of the page), and on our own [[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.