post more problems
authorjim <jim@web>
Mon, 6 Apr 2015 02:07:46 +0000 (22:07 -0400)
committerLinux User <ikiwiki@localhost.members.linode.com>
Mon, 6 Apr 2015 02:07:46 +0000 (22:07 -0400)
exercises/_assignment8.mdwn

index a05707a..a0b05d9 100644 (file)
-Binding more than one variable at a time
-----------------------------------------
+This is the assignment for weeks 8-9, on Reader and State monads.
+
+<!--
+1. When discussing safe division, we worked with operators like `map2 (+)` which just did their ordinary thing, only now lifted up into working on "boxed" or monadic values. Also there was a special division operator, which interacted with the new possibilities presented by the Option/Maybe monad. Instead of this special division operator and the Option monad, show us how to write expressions in the Reader monad with special `getx` operators. That is, instead of representing computations like `(2+3)/0/1`, now you will represent computations like `(2+x)+1`. To keep things simple, suppose that your language only allows three variables `x`, `y`, and `z`, and you can represent the `env` as a triple of `int`s. For this problem you don't need to demonstrate how to implement binding expressions like `let x = 3 in ...`. You just need to compute the value of possibly open expressions, relative to a supplied `env` that gives values for `x` and `y` and `z`.
+
+2. Okay, now what changes do you need to make to add in expressions like `let x = 3 in ...`
+-->
+
 
 1. Jacobson's reader monad only allows for establishing a single binding
 relationship at a time.  It requires considerable cleverness to deploy
 her combinators in a way that establishes multiple binding
 relationships, as in 
 
 
 1. Jacobson's reader monad only allows for establishing a single binding
 relationship at a time.  It requires considerable cleverness to deploy
 her combinators in a way that establishes multiple binding
 relationships, as in 
 
-    John_x thinks Mary_y said he_x likes her_y.
+        John_x thinks Mary_y said he_x likes her_y.
 
 
-See her 1999 paper for details.
+    See her 1999 paper for details.
 
 
-Here is [[code for the simple arithmetic reader monad discussed in the
-lecture notes|code/arith1.ml]]. It computes
+    Here is [[code for the arithmetic tree Chris presented in week 8|code/arith1.ml]]. It computes
 `\x. (+ 1 (* (/ 6 x) 4))`.  Your task is to modify it to compute
 `\x. (+ 1 (* (/ 6 x) 4))`.  Your task is to modify it to compute
-`\x\y.(+ 1 (* (/ 6 x) y))`.  You will need to modify five lines.
+`\x y. (+ 1 (* (/ 6 x) y))`.  You will need to modify five lines.
 The first one is the type of a boxed int.  Instead of `type num = int
 -> int`, you'll need
 
 The first one is the type of a boxed int.  Instead of `type num = int
 -> int`, you'll need
 
-    type num = int -> int -> int
+        type num = int -> int -> int
 
 
-The second and third are the definitions of mid and map2.  The fourth
-is the one that encodes the variable x, the line that begins `(Leaf
+    The second and third are the definitions of `mid` and `map2`. The fourth
+is the one that encodes the variable `x`, the line that begins `(Leaf
 (Num (fun x -> ...`.  The fifth line you need to modify is the one
 that replaces "4" with "y".  When you have these lines modified,
 you should be able to execute the following expression:
 
 (Num (fun x -> ...`.  The fifth line you need to modify is the one
 that replaces "4" with "y".  When you have these lines modified,
 you should be able to execute the following expression:
 
-    # match eval t2 with Leaf (Num f) -> f 2 4;;
-    - : int = 13
+        # match eval t2 with Leaf (Num f) -> f 2 4;;
+        - : int = 13
+
+2. Based on the evaluator code from the assignment from week 7, and what you've learned about the Reader monad,
+enhance the arithmetic tree code to handle an arbitrary set of free variables. Don't use Juli8 libraries for this; just do it by hand.
+Return to the original code (that is, before the modifications required by the previous problem).
+
+    Start like this:
 
 
-2. Based on the evaluator code from the assignment from week 7,
-enhance the code to handle an arbitrary set of free variables.  
-Return to the original code (before executing the modifications
-required by exercise 1).
+        type env = string -> int
+        type num = env -> int
+        let my_env = fun var -> match var with "x" -> 2 | "y" -> 4 | _ -> 0;;
 
 
-Start like this:
+    When you have it working, try
 
 
-    type env = string -> int
-    type num = env -> int
-    let g = fun var -> match var with "x" -> 2 | "y" -> 4 | _ -> 0;;
+        # match eval t2 with Leaf (Num f) -> f my_env;;
+        - : int = 13
 
 
-When you have it working, try
+    For this problem you don't need to demonstrate how to implement binding expressions like `let x = 3 in ...`. You just need to compute the value of possibly open expressions, relative to the supplied `env`.
 
 
-    # match eval t2 with Leaf (Num f) -> f g;;
-    - : int = 13
+3. Okay, now what changes do you need to make to add in expressions like `let x = 3 in ...`
 
 
-3. Add in the maybe monad.  Start here:
+4. Add in the Option/Maybe monad.  Start here:
 
         type num = env -> int option
 
 
         type num = env -> int option
 
-   Show that your code handles division by zero gracefully.
+    Show that your code handles division by zero gracefully.
+
+5. Consider the following code which uses the Juli8 libraries for OCaml.
+
+        module S = Monad.State(struct type store = int end);;
+        let xx = S.(mid 1 >>= fun x -> put 20 >> modify succ >> get >>= fun y -> mid [x;y]) in
+        S.run xx 0
+
+    Don't try running the code yet. Instead, get yourself into a position to predict what it will do, by reading the past few discussions about the State monad. After you've made a prediction, then run the code and see if you got it right.
+
+6. Here's another one:
+
+        (* start with module S = ... as before *)
+        let yy = S.(let xx = modify succ >> get in
+           xx >>= fun x1 -> xx >>= fun x2 -> xx >>= fun x3 -> mid [x1;x2;x3]) in
+        S.run yy 0
+
+    What is your prediction? What did OCaml actually evaluate this to?
+
+7. Suppose you're trying to use the State monad to keep a running tally of how often certain arithmetic operations have been used in computing a complex expression. You've come upon the design plan of using the same State monad module `S` from the previous problems, and defining a function like this:
+
+        let counting_plus xx yy = S.(map2 (+) xx yy >>= tick)
+
+    How should you define the operation `tick` to make this work? The intended behavior is that after running:
+
+        let zz = counting_plus (S.mid 1) (counting_plus (S.mid 2) (S.mid 3)) in
+        S.run zz 0
+
+    you should get a payload of `6` (`1+(2+3)`) and a final `store` of `2` (because `+` was used twice).
+
+8. Instead of the design in the previous problem, suppose you had instead chosen to do things this way:
+
+        let counting_plus xx yy = S.(tock >> map2 (+) xx yy)
+
+    How should you define the operation `tock` to make this work, with the same behavior as before?
+
+9. Here is how to create a monadic stack of a Reader monad transformer wrapped around an underlying Option monad:
+
+        module O = Monad.Option (* not really necessary *)
+        module R = Monad.Reader(struct type env = (* whatever *) end)
+        module RO = R.T(O) (* wrap R's Transformer around O *)
+
+    You can inspect the types that result by saying `#show RO.result` (in OCaml version >= 4.02), or by running:
+
+        let env0 = (* some appropriate env, depending on how you defined R *) in
+        let xx = RO.(mid 1) in RO.run xx env0
+
+    and inspecting the type of the result. Okay, here are some questions about various monad transformers. Use OCaml to help you answer them. Which combined monad has the type of an optional list (that is, either `None` or `Some [...]`): an Option transformer wrapped around an underlying List monad, or a List transformer wrapped around an underlying Option monad? Which combined monad has the type of a function from `store`s to a pair `('a list, store)`: a List transformer wrapped around an underlying State monad or a State transformer wrapped around an underlying List monad?
+
+The last two problems are non-monadic.
+
+10. This is a question about native mutation mechanisms in languages that have them, like OCaml or Scheme. What an expression like this:
+
+        let cell = ref 0 in
+        let incr c = (let old = !cell in let () = cell := old + 1 in ()) in
+        (incr cell, !cell, incr cell, incr cell)
+
+    will evaluate to will be `((), n, (), ())` for some number `n` between `0` and `3`. But what number is sensitive to the details of OCaml's evaluation strategy for evaluating tuple expressions. How can you avoid that dependence? That is, how can you rewrite such code to force it that the values in the triple have been evaluated left-to-right? Show us a strategy that works no matter what the expressions in the tuple are, not just these particular ones. (But you can assume that the expressions all terminate.)
+
+11. In the evaluator code for [[Week 7 homework|/exercises/assignment7]], we left the `LetRec` portions unimplemented. How might we implement these for the second, `env`-using interpreter? One strategy would be to interpret expressions like:
+
+        letrec f = \x. BODY in
+        TERM
+
+    as though they really read:
+
+        let f = FIX (\f x. BODY) in
+        TERM
+
+    for some fixed-point combinator `FIX`. And that would work, supposing you use some fixed point combinator like the "primed" ones we showed you earlier that work with eager/call-by-value evaluation strategies. But for this problem, we want you to approach the task a different way.
+
+    Begin by deleting all the `module VA = ...` code that implements the substitute-and-repeat interpreter. Next, change the type of `env` to be an `(identifier * bound) list`. Add a line after the definition of that type that says `and bound = Plain of result | Recursive of identifier * identifier * term * env`. The idea here is that some variables will be bound to ordinary `result`s, and others will be bound to special structures we've made to keep track of the recursive definitions. These special structures are akin to the `Closure of identifier * term * env` we already added to the `term` (or really more properly `result`) datatype. For `Closure`s, the single `identifier` is the bound variable, the `term` is the body of the lambda abstract`, and the `env` is the environment that is in place when some variable is bound to this lambda abstract. Those same parameters make up the last three arguments of our `Recursive` structure. The first argument in the `Recursive` structure is to hold the variable that our `letrec` construction binds to the lambda abstract. That is, in:
+
+        letrec f = \x. BODY in
+        TERM
+
+both of the variables `f` and `x` need to be interpreted specially when we evaluate `BODY`, and this is how we keep track of which variable is `f`.
+
+    Just making those changes will require you to change some other parts of the interpreter to make it still work. Before trying to do anything further with `letrec`, try finding what parts of the code need to be changed to accommodate these modifications to our types. See if you can get the interpreter working again as well as it was before.
+
+    OK, once you've done that, then add an extra line:
+
+        | LetRec of identifier * identifier * term * term
+
+    to the definition of the `term` datatype. (For `letrec IDENT1 = \IDENT2. TERM1 in TERM2`.) Now what will you need to add to the `eval` function to get it to interpret these terms properly? This will take some thought, and a good understanding of how the other clauses in the `eval` function are working.