From e22e8f121d8f32653a52791bef132f163c76ecf5 Mon Sep 17 00:00:00 2001 From: jim Date: Sun, 22 Mar 2015 22:24:53 -0400 Subject: [PATCH] polish --- topics/_week8_using_monads.mdwn | 106 +++++++++++++++++++++++++++------------- 1 file changed, 73 insertions(+), 33 deletions(-) diff --git a/topics/_week8_using_monads.mdwn b/topics/_week8_using_monads.mdwn index f23ef507..cdaa949e 100644 --- a/topics/_week8_using_monads.mdwn +++ b/topics/_week8_using_monads.mdwn @@ -1,14 +1,15 @@ -Some applications of monadic machinery... +As we discussed in class, there are clear patterns shared between lists and option types and trees, so perhaps you can see why people want to figure out 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. -## Safe division ## +OCaml's `/` operator expresses integer division, which throws away any remainder, thus: -As we discussed in class, there are clear patterns shared between lists and option types and trees, so perhaps you can see why people want to figure out 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. + # 11/3;; + - : int = 3 Integer division presupposes that its second argument (the divisor) is not zero, upon pain of presupposition failure. Here's what my OCaml interpreter says: - # 12/0;; + # 11/0;; Exception: Division_by_zero. Say we want to explicitly allow for the possibility that @@ -25,7 +26,7 @@ So if a division is normal, we return some number, but if the divisor is zero, we return `None`. As a mnemonic aid, we'll prepend a `safe_` to the start of our new divide function.
-let safe_div (x:int) (y:int) =
+let safe_div (x : int) (y : int) =
   match y with
     | 0 -> None
     | _ -> Some (x / y);;
@@ -49,11 +50,12 @@ the output of the safe-division function as input for further division
 operations. So we have to jack up the types of the inputs:
 
 
-let safe_div2 (u:int option) (v:int option) =
+let safe_div2 (u : int option) (v : int option) =
   match u with
   | None -> None
   | Some x ->
       (match v with
+      | None -> None
       | Some 0 -> None
       | Some y -> Some (x / y));;
 
@@ -75,7 +77,7 @@ I prefer to line up the `match` alternatives by using OCaml's
 built-in tuple type:
 
 
-let safe_div2 (u:int option) (v:int option) =
+let safe_div2 (u : int option) (v : int option) =
   match (u, v) with
   | (None, _) -> None
   | (_, None) -> None
@@ -104,17 +106,23 @@ val safe_add : int option -> int option -> int option = 
 *)
 
+So now, wherever before our operations expected an `int`, we'll instead +have them accept an `int option`. A `None` input signals that +something has gone wrong upstream. + This works, but is somewhat disappointing: the `safe_add` operation doesn't trigger any presupposition of its own, so it is a shame that it needs to be adjusted because someone else might make trouble. -But we can automate the adjustment, using the monadic machinery we introduced above. +But we can automate the adjustment, using the monadic machinery we introduced before. As we said, there needs to be different `>>=`, `map2` and so on operations for each -monad or box type we're working with. +Monad or box type we're working with. Haskell finesses this by "overloading" the single symbol `>>=`; you can just input that symbol and it will calculate from the context of the surrounding type constraints what -monad you must have meant. In OCaml, the monadic operators are not pre-defined, but we will -give you a library that has definitions for all the standard monads, as in Haskell. +Monad you must have meant. In OCaml, the monadic operators are not pre-defined, but we will +give you a library that has definitions for all the standard Monads, as in Haskell. But you +will need to explicitly specify which Monad you mean to be deploying. + For now, though, we will define our `>>=` and `map2` operations by hand:
@@ -139,6 +147,12 @@ Haskell has an even more user-friendly notation for defining `safe_div3`, namely
                         y <- v;
                         if 0 == y then Nothing else Just (x `div` y)}
 
+You can read more about that here:
+
+*	[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)
+
+
 Let's see our new functions in action:
 
 
@@ -152,11 +166,11 @@ Let's see our new functions in action:
 *)
 
-Compare the new definitions of `safe_add3` and `safe_div3` closely: the definition -for `safe_add3` shows what it looks like to equip an ordinary operation to -survive in dangerous presupposition-filled world. Note that the new +Our definition for `safe_add3` shows what it looks like to equip an ordinary operation to +survive in dangerous presupposition-filled world. We just need to `mapN` it "into" the +Maybe monad, where `N` is the function's adicity. Note that the new definition of `safe_add3` does not need to test whether its arguments are -`None` values or real numbers---those details are hidden inside of the +`None` values or genuine numbers---those details are hidden inside of the `bind` function. Note also that our definition of `safe_div3` recovers some of the simplicity of @@ -165,7 +179,17 @@ add exactly what extra is needed to track the no-division-by-zero presupposition need to keep track of what other presuppositions may have already failed for whatever reason on our inputs. -(Linguistics note: Dividing by zero is supposed to feel like a kind of +So what the monadic machinery gives us here is a way to _separate_ thinking +about error conditions (such as trying to divide by zero) from thinking about normal +arithmetic computations. When we're adding or multiplying, we don't have to worry about generating +any new errors, so we would rather not force these operations to explicitly +track the difference between `int`s and `int option`s. A linguistics analogy we'll +look at soon is that when we're giving the lexical entry for an ordinary +extensional verb, we'd rather not be forced to talk about possible worlds. In each case, +we instead just have a standard way of "lifting" (`mapN`ing) the relevant notions into +the fancier type environment we ultimately want to work in. + +Dividing by zero is supposed to feel like a kind of presupposition failure. If we wanted to adapt this approach to building a simple account of presupposition projection, we would have to do several things. First, we would have to make use of the @@ -178,20 +202,36 @@ theory of accommodation, and a theory of the situations in which material within the sentence can satisfy presuppositions for other material that otherwise would trigger a presupposition violation; but, not surprisingly, these refinements will require some more -sophisticated techniques than the super-simple Option/Maybe monad.) - - -## Scratch, more... ## - -We've just seen a way to separate thinking about error conditions -(such as trying to divide by zero) from thinking about normal -arithmetic computations. We did this by making use of the `option` -type: in each place where we had something of type `int`, we put -instead something of type `int option`, which is a sum type consisting -either of one choice with an `int` payload, or else a `None` choice -which we interpret as signaling that something has gone wrong. - -The goal was to make normal computing as convenient as possible: when -we're adding or multiplying, we don't have to worry about generating -any new errors, so we would rather not think about the difference -between `int`s and `int option`s. +sophisticated techniques than the super-simple Option/Maybe Monad. + +To illustrate some of the polymorphism, here's how we could `map1` the `is_even` function: + + # let is_even x = (x mod 2 = 0);; + val is_even : int -> bool = + # let map (g : 'a -> 'b) (u : 'a option) = u >>= fun x -> Some (g x);; + val map : ('a -> 'b) -> 'a option -> 'b option = + # map (is_even);; + - : int option -> bool option = + +Wherever we have a well-defined monad, we can define the `mapN` operations for them in terms +of their `>>=` and `mid`. The general pattern is: + + mapN (g : 'a1 -> ... 'an -> 'result) (u1 : 'a1 option) ... (un : 'an option) : 'result option = + u1 >>= (fun x1 -> ... un >>= (fun xn -> mid (g x1 ... xn)) ...) + +Our above definitions of `map` and `mapN` were of this form, except we just +explicitly supplied the definition of `mid` for the Option/Maybe monad (namely, in OCamlese, the constructor `Some`). +If you substitute in the definition of `>>=`, you can see these are equivalent to: + + map (g : 'a -> 'b) (u : 'a option) = + match u with + | None -> None + | Some x -> Some (g x) + + map2 (g : 'a -> 'b -> 'c) (u : 'a option) (v : 'b option) = + match u with + | None -> None + | Some x -> + (match v with + | None -> None + | Some y -> Some (g x y));; -- 2.11.0