[[!toc]] The seminar is now going to begin talking about more **imperatival** or **effect**-like elements in programming languages. The only effect-like element we've encountered so far is the possibility of divergence, in languages that permit fixed point combinators and so have the full power of recursion. What it means for something to be effect-like, and why this counts as an example of such, will emerge. Other effect-like elements in a language include: printing; continuations (which we'll study more in the coming weeks) and exceptions (like OCaml's `failwith "message"` or `raise Not_found`); and **mutation**. This last notion is our topic this week. ## Mutation## What is mutation? It's helpful to build up to this in a series of fragments. For present pedagogical purposes, we'll be using a made-up language that's syntactically similar to, but not quite the same as, OCaml. (It's not quite Kapulet either.) This should seem entirely familiar: [A] let y = 1 + 2 in let x = 10 in (x + y, 20 + y) ; evaluates to (13, 23) In our next fragment, we re-use a variable that had been bound to another value in a wider context: [B] let y = 2 in ; will be shadowed by the binding on the next line let y = 3 in (10 + y, 20 + y) ; evaluates to (13, 23) As you can see, the narrowest assignment is what's effective. This is just like in predicate logic: consider `∃y (Fy and ∃y ~Fy)`. The computer-science terminology to describe this is that the narrower assignment of `y` to the value 3 **shadows** the wider assignment to 2. I call attention to this because you might casually describe it as "changing the value that y is assigned to." But what we'll see below is a more exotic phenomenon that merits that description better. In the previous fragments, we bound the variables `x` and `y` to `int`s. We can also bind variables to function values, as here: [C] let f = (\x y. x + y + 1) in (f 10 2, f 20 2) ; evaluates to (13, 23) If the expression that evaluates to a function value has a free variable in it, like `y` in the next fragment, it's interpreted as bound to whatever value `y` has in that expression's lexical context: [D] let y = 3 in let f = (\x. x + y) in let y = 2 in (f 10, y, f 20) ; evaluates to (13, 2, 23) Other choices about how to interpret free variables are also possible (you can read about "lexical scope" versus "dynamic scope"), but what we do here is the contemporary norm in functional programming languages, and seems to be easiest for programmers to reason about. Sometimes bindings are shadowed merely in a temporary, local context, as here: [E] let y = 3 in let f = (\x. let y = 2 in ; here the most local binding for y applies x + y) in ; here the binding of y to 2 has expired (y, f 10, y, f 20) ; evaluates to (3, 12, 3, 22) Notice that the `y`s in the tuple at the end use the outermost binding of `y` to `3`, but the `y` in `x + y` in the body of the `f` function uses the more local binding. OK, now we're ready for our main event, **mutable variables.** We'll introduce new syntax to express an operation where we're not merely *shadowing* a wider binding, but *changing* or *mutating* that binding. The new syntax will show up both when we introduce the variable, using `var y = ...` rather than `let y = ...`; and also when we change `y`'s value using `set`. [F] var y = 3 in let f = (\x. set y to 2 then x + y) in ; here the change in what value y is bound to *sticks* ; because we *mutated* the value of the *original* variable y ; instead of introducing a new y with a narrower scope (y, f 10, y, f 20) ; evaluates to (3, 12, 2, 22) Notice the difference in the how the second `y` is evaluated in the tuple at the end. By the way, I am assuming here that the tuple gets evaluated left-to-right. Other languages may or may not conform to that. OCaml doesn't always. In languages that have native syntax for mutation, there are two styles in which it can be expressed. The *implicit style* is exemplified in fragment [F] above, and also in languages like C: { int y = 3; // this is like "var y = 3 in ..." ... y = 2; // this is like "set y to 2 then ..." return x + y; // this is like "x + y" } A different possibility is the *explicit style* for handling mutation. Here we explicitly create and refer to new "reference cells" to hold our values. When we mutate a variable's value, we leave the variable assigned to the same reference cell, but we modify that reference cell's contents. The same thing happens in the semantic machinery underlying implicit-style mutable variables, but there it's implicit --- the reference cells aren't themselves expressed by any term in the object language. In explicit-style mutation, they are. OCaml has explicit-style mutation. It looks like this: let ycell = ref 3 (* this creates a new reference cell *) ... in let () = ycell := 2 in (* this changes the contents of that cell to 2 *) (* the return value of doing so is () *) (* other return values could also be reasonable: *) (* such as the old value of ycell, the new value, an arbitrary int, and so on *) x + !ycell (* the !ycell operation "dereferences" the cell---it retrieves the value it contains *) Scheme is similar. There are various sorts of reference cells available in Scheme. The one most like OCaml's `ref` is a `box`. Here's how we'd write the same fragment in Scheme: (let ([ycell (box 3)]) ... (set-box! ycell 2) (+ x (unbox ycell))) C has explicit-style mutable variables, too, which it calls *pointers*. But simple variables in C are already mutable, in the implicit style. Scheme also has both styles of mutation. In addition to the explicit boxes, Scheme also lets you mutate unboxed variables: (begin (define y 3) (set! y 2) y) ; evaluates to 2 When dealing with explicit-style mutation, there's a difference between the types and values of `ycell` and `!ycell` (or in Scheme, `(unbox ycell)`). The former has the type `int ref`: the variable `ycell` is assigned a reference cell that contains an `int`. The latter has the type `int`, and has whatever value is now stored in the relevant reference cell. In an implicit-style framework though, we only have the resources to refer to the contents of the relevant reference cell. The variables `y` in fragment [F] or in the C snippet above have the type `int`, and only ever evaluate to `int` values. ##Controlling order## When we're dealing with mutable variables (or any other kind of effect), order matters. For example, it would make a big difference whether I evaluated `let z = !ycell` before or after evaluating `ycell := !ycell + 1`. Before this point, order never mattered except sometimes it played a role in avoiding divergence. OCaml does *not* guarantee what order expressions will be evaluated in arbitrary contexts. For example, in the following fragment, you cannot rely on `expression_a` being evaluated before `expression_b` before `expression_c`: let triple = (expression_a, expression_b, expression_c) OCaml does however guarantee that different let-expressions are evaluated in the order they lexically appear. So in the following fragment, `expression_a` *will* be evaluated before `expression_b` and that before `expression_c`: let a = expression_a in let b = expression_b in expression_c Scheme does the same. (*If* you use Scheme's `let*`, but not if you use its `let`. I agree this is annoying.) If `expression_a` and `expression_b` evaluate to (), for instance if they're something like `ycell := !ycell + 1`, that can also be expressed in OCaml as: let () = expression_a in let () = expression_b in expression_c And OCaml has a syntactic shorthand for this form, namely to use semi-colons: expression_a; expression_b; expression_c This is not the same role that semi-colons play in list expressions, like `[1; 2; 3]`. To be parsed correctly, these semi-colon'ed complexes sometimes need to be enclosed in parentheses or a `begin ... end` construction: (expression_a; expression_b; expression_c) begin expression_a; expression_b; expression_c end Scheme has a construction similar to the latter: (begin (expression_a) (expression_b) (expression_c)) Though often in Scheme, the `(begin ...)` is implicit and doesn't need to be explicitly inserted, as here: (lambda (x) (expression_a) (expression_b) (expression_c)) Another way to control evaluation order, you'll recall from previous discussion, is to use **thunks**. These are functions that only take the uninformative `()` as an argument, such as this: let f () = ... in ... or this: let f = fun () -> ... in ... In Scheme these are written as functions that take 0 arguments: (let* ([f (lambda () ...)]) ...) or: (define (f) ...) ... How could such functions be useful? Well, as always, the context in which you build a function need not be the same as the one in which you apply it to arguments. So for example: let ycell = ref 1 in let incr_y () = ycell := !ycell + 1 in let y = !ycell in incr_y () in y We don't apply (or call or execute or however you want to say it) the function `incr_y` until after we've extracted `ycell`'s value and assigned it to `y`. So `y` will get assigned `1`. If on the other hand we called `incr_y ()` before evaluating `let y = !ycell`, then `y` would have gotten assigned a different value. In languages with mutable variables, the free variables in a function definition are often taken to refer back to the same *reference cells* they had in their lexical contexts, and not just their original value. So if we do this for instance: let factory (starting_value : int) = let free_var = ref starting_value in (* `free_var` will be free in the bodies of the next two functions *) let getter () = !free_var in let setter (new_value : int) = free_var := new_value in (* here's what `factory starting_value` returns *) (getter, setter) in let (getter, setter) = factory 1 in let first = getter () in let () = setter 2 in let second = getter () in let () = setter 3 in let third = getter () in (first, second, third) At the end, we'll get `(1, 2, 3)`. The reference cell that gets updated when we call `setter` is the same one that gets fetched from when we call `getter`. This should seem very intuitive here, since we're working with explicit-style mutation. When working with a language with implicit-style mutation, it can be more surprising. For instance, here's the same fragment in Python, which has implicit-style mutation: def factory (starting_value): free_var = starting_value def getter (): return free_var def setter (new_value): # the next line indicates that we're using the # free_var from the surrounding function, not # introducing a new local variable with the same name nonlocal free_var free_var = new_value return getter, setter getter, setter = factory (1) first = getter () setter (2) second = getter () setter (3) third = getter () (first, second, third) Here, too, just as in the OCaml fragment, all the calls to getter and setter are working with a single mutable variable `free_var`. If you've got a copy of *The Seasoned Schemer*, which we recommended for the seminar, see the discussion at pp. 91-118 and 127-137. If however you call the `factory` function twice, even if you supply the same `starting_value`, you'll get independent `getter`/`setter` pairs, each of which have their own, separate `free_var`. In OCaml: let factory (starting_val : int) = ... (* as above *) in let (getter, setter) = factory 1 in let (getter', setter') = factory 1 in let () = setter 2 in getter' () Here, the call to `setter` only mutated the reference cell associated with the `getter`/`setter` pair. The reference cell associated with `getter'` hasn't changed, and so `getter' ()` will still evaluate to `1`. Notice in these fragments that once we return from inside the call to `factory`, the `free_var` mutable variable is no longer accessible, except through the helper functions `getter` and `setter` that we've provided. This is another way in which a thunk like `getter` can be useful: it still has access to the `free_var` reference cell that was created when it was, because its free variables are interpreted relative to the context in which `getter` was built, even if that context is otherwise no longer accessible. What `getter ()` evaluates to, however, will very much depend on *when* we evaluate it --- in particular, it will depend on which calls to the corresponding `setter` were evaluated first. ##Referential opacity## In addition to order-sensitivity, when you're dealing with mutable variables you also give up a property that computer scientists call "referential transparency." It's not obvious whether they mean exactly the same by that as philosophers and linguists do, or only something approximately the same. The core idea to referential transparency is that when the same value is supplied to a context, the whole should always evaluate the same way. Mutation makes it possible to violate this. Consider: let ycell = ref 1 in let plus_y x = x + !ycell in let first = plus_y 1 in (* first is assigned the value 2 *) ycell := 2; let second = plus_y 1 in (* second is assigned the value 3 *) first = second (* not true! *) Notice that the two invocations of `plus_y 1` yield different results, even though the same value is being supplied as an argument to the same function. Similarly, functions like these: let f cell = !cell let g cell = cell := !cell + 1; !cell may return different results each time they're invoked, even if they're always supplied one and the same reference cell as argument. Computer scientists also associate referential transparency with a kind of substitution principle, illustrated here: let x = 1 in (x, x) should evaluate the same as: let x = 1 in (x, 1) or: (1, 1) Notice, however, that when mutable variables are present, the same substitution patterns can't always be relied on: let ycell = ref 1 in ycell := 2; !ycell (* evaluates to 2 *) (ref 1) := 2; !(ref 1) (* creates a ref 1 cell and changes its contents *) (* then creates a *new* ref 1 cell and returns *its* contents *) (* so evaluates to 1 *) ##How to implement explicit-style mutable variables## We'll think about how to implement explicit-style mutation first. We suppose that we add some new syntactic forms to a language, let's call them `newref`, `getref`, and `putref`. And now we want to expand the semantics for the language so as to interpret these new forms. Well, part of our semantic machinery will be an assignment function or environment, call it `e`. Perhaps we should keep track of the *types* of the variables and values we're working with, but we won't pay much attention to that now. In fact, we won't even bother much at this point with the assignment function. Below we'll pay more attention to it. In addition to the assignment function, we'll also need a way to keep track of how many reference cells have been "allocated" (using `newref`), and what their current values are. We'll suppose all the reference cells are organized in a single data structure we might call a table or **store**. This might be a big heap of memory. For our purposes, we'll suppose that reference cells only ever contain `int`s, and we'll let the store be a list of `int`s. We won't suppose that the metalanguage we use to express the semantics of our mutation-language itself has any mutation facilities. Instead, we'll think about how to model mutation in a wholly declarative or functional or *static* metalanguage. In many languages, including OCaml, the first position in a list is indexed `0`, the second is indexed `1` and so on. If a list has length `2`, then there won't be any value at index `2`; that will be the "next free location" in the list. Before we brought mutation on the scene, our language's semantics will have looked something like this: > \[[expression]]e = result Now we're going to relativize our interpretations not only to the environment `e`, but also to the current store, which I'll label `s`. Additionally, we're going to want to allow that evaluating some functions might *change* the store, perhaps by allocating new reference cells or perhaps by modifying the contents of some existing cells. So the interpretation of an expression won't just return a result; it will also return a possibly updated store. We'll suppose that our interpretation function does this quite generally, even though for many expressions in the language, the store that's returned will be the same one that the interpretation function started with: > \[[expression]]e s = (result, s') For expressions we already know how to interpret, you can by default expect `s'` to just be `s`. An exception is complex expressions like `let var = expr1 in expr2`. Part of interpreting this will be to interpret the sub-expression `expr1`, and we have to allow that in doing that, the store may have already been updated. We want to use that possibly updated store when interpreting `expr2`. Like this: let rec eval term e s = match term with ... | Let (var, expr1, expr2) -> let (res1, s') = eval expr1 e s (* s' may be different from s *) (* now we evaluate expr2 in a new environment where var has been associated with the result of evaluating expr1 in the current environment *) eval expr2 ((var, res1) :: e) s' ... Similarly: ... | Apply (Apply(PrimitiveAddition, expr1), expr2) -> let (res1, s') = eval expr1 e s in let (res2, s'') = eval expr2 e s' in (res1 + res2, s'') ... Let's consider how to interpet our new syntactic forms `newref`, `getref`, and `putref`: 1. When `expr` evaluates to `starting_val`, then **newref expr** should allocate a new reference cell in the store and insert `starting_val` into that cell. It should return some "key" or "index" or "pointer" to the newly created reference cell, so that we can do things like: let ycell = newref 1 in ... and be able to refer back to that cell later by using the result that we assigned to the variable `ycell`. In our simple implementation, we're letting the store just be an `int list`, and we can let the "keys" be indexes in that list, which are (also) just `int`s. Somehow we should keep track of which variables are assigned `int`s as `int`s and which are assigned `int`s as indexes into the store. So we'll create a special type to wrap the latter: type store_index = Index of int Our interpretation function will look something like this: let rec eval term e s = match term with ... | Newref (expr) -> let (starting_val, s') = eval expr e s in (* note that s' may be different from s, if expr itself contained any mutation operations *) (* now we want to retrieve the next free index in s' *) let new_index = List.length s' in (* now we want to insert starting_val there; the following is an easy but inefficient way to do it *) let s'' = List.append s' [starting_val] in (* now we return a pair of a wrapped new_index, and the new store *) (Index new_index, s'') ... 2. When `expr` evaluates to a `store_index`, then **getref expr** should evaluate to whatever value is at that index in the current store. (If `expr` evaluates to a value of another type, `getref expr` is undefined.) In this operation, we don't change the store at all; we're just reading from it. So we'll return the same store back unchanged (assuming it wasn't changed during the evaluation of `expr`). let rec eval term e s = match term with ... | Getref (expr) -> let (Index n, s') = eval expr e s in (* s' may be different from s, if expr itself contained any mutation operations *) (List.nth s' n, s') ... 3. When `expr1` evaluates to a `store_index` and `expr2` evaluates to an `int`, then **putref expr1 expr2** should have the effect of changing the store so that the reference cell at that index now contains that `int`. We have to make a decision about what result the `putref ...` call should itself evaluate to; OCaml makes this `()` but other choices are also possible. Here I'll just suppose we've got some appropriate value in the variable `dummy`. let rec eval term e s = match term with ... | Putref (expr1, expr2) -> let (Index n, s') = eval expr1 e s in (* note that s' may be different from s, if expr1 itself contained any mutation operations *) let (new_value, s'') = eval expr2 e s' in (* now we create a list which is just like s'' except it has new_value in index n *) (* the following could be expressed in Juli8 as `modify m (fun _ -> new_value) xs` *) let rec replace_nth xs m = match xs with | [] -> failwith "list too short" | x::xs when m = 0 -> new_value :: xs | x::xs -> x :: replace_nth xs (m - 1) in let s''' = replace_nth s'' n in (dummy, s''') ... ##How to implement implicit-style mutable variables## With implicit-style mutation, we don't have new syntactic forms like `newref` and `getref`. Instead, we just treat ordinary variables as being mutable. You could if you wanted to have some variables be mutable and others not; perhaps the first sort are written in Greek and the second in Latin. But for present purposes, we will suppose all variables in our language are mutable. We will still need a store to keep track of reference cells and their current values, just as in the explicit-style implementation. This time, every variable will be associated with an index into the store. So this is what we'll have our assignment function keep track of. The assignment function will bind variables to indexes into the store, rather than to the variables' current values. The variables will only indirectly be associated with "their values" by virtue of the joint work of the assignment function and the store. This brings up an interesting conceptual distinction. Formerly, we'd naturally think that a variable `x` is associated with only one type, and that that's the type that the expression `x` would *evaluate to*, and also the type of value that the assignment function *bound* `x` to. However, in the current framework these two types come apart. The assignment function binds `x` to an index into the store, and what the expression `x` evaluates to will be the value at that location in the store, which will usually be some type other than an index into a store, such as a `bool` or a `string`. To handle implicit-style mutation, we'll need to re-implement the way we interpret expressions like `x` and `var x = expr1 in expr2`. We will also have just one new syntactic form, `set x to expr1 then expr2`. (The `then` here is playing the role of the sequencing semicolon in OCaml.) Here's how to implement these. We'll suppose that our assignment function is list of pairs, as above and as in [week7](/reader_monad_for_variable_binding). LINK TODO let rec eval term e s = match term with ... | Var (var : identifier) -> let index = List.assoc var e in (* retrieve the value at that index in the current store *) let res = List.nth s index in (res, s) (* instead of `let x = ...` we now have `var x = ...`, for which I'll use the `Letvar` tag *) | Letvar ((var : identifier), expr1, expr2) -> let (starting_val, s') = eval expr1 e s in (* get next free index in s' *) let new_index = List.length s' in (* insert starting_val there *) let s'' = List.append s' [starting_val] in (* evaluate expr2 using a new assignment function and store *) eval expr2 ((var, new_index) :: e) s'' | Set ((var : identifier), expr1, expr2) -> let (new_value, s') = eval expr1 e s in (* lookup which index is associated with Var var *) let index = List.assoc var e in (* now we create a list which is just like s' except it has new_value at index *) let rec replace_nth xs m = match xs with | [] -> failwith "list too short" | x::xs when m = 0 -> new_value :: xs | x::xs -> x :: replace_nth xs (m - 1) in let s'' = replace_nth s' index in (* evaluate expr2 using original assignment function and new store *) eval expr2 e s'' ##How to implement mutation with a State monad## It's possible to do all of this monadically, instead of adding new syntactic forms and new interpretation rules to a language's semantics. The patterns we use to do this in fact closely mirror the machinery described above. We call this a State monad. It's a lot like the Reader monad, except that with the Reader monad, we could only read from the environment. We did have the possibility of interpreting sub-expressions inside a "shifted" environment, but as you'll see, that corresponds to the "shadowing" behavior described before, not to the mutation behavior that we're trying to implement now. With a State monad, we call our book-keeping apparatus a "store" instead of an environment, and this time we are able to both read from it and write to it. To keep things simple, we'll work here with the simplest possible kind of store, which only holds a single value. One could also have stores that were composed of a list of values, of a length that could expand or shrink, or even more complex structures. Here's the implementation of the State monad, together with an implementation of the Reader monad for comparison: type env = (identifier * int) list (* alternatively, an env could be implemented as type identifier -> int *) type 'a reader = env -> 'a let reader_mid (x : 'a) : 'a reader = fun e -> x let reader_mbind (xx : 'a reader) (k : 'a -> 'b reader) : 'b reader = fun e -> let x = xx e in let yy = k x in yy e type store = int (* very simple store, holds only a single int *) (* this corresponds to having only a single mutable variable *) type 'a state = store -> ('a, store) let state_mid (x : 'a) : 'a state = fun s -> (x, s) let state_mbind (xx : 'a state) (k : 'a -> 'b state) : 'b state = fun s -> let (x, s') = xx s in let yy = k x in yy s' Notice the similarities (and differences) between the implementation of these two monads. With the Reader monad, we also had some special-purpose operations, beyond its general monadic operations. Two to focus on were `asks` and `shift`. We would call `asks` with a helper function like `lookup "x"` that looked up a given variable in an environment. And we would call `shift` with a helper function like `insert "x" new_value` that operated on an existing environment to return a new one. With the State monad, we'll also have some special-purpose operations. We'll consider two basic ones here. One will be to retrieve what is the current store. This is like the Reader monad's `asks (lookup "x")`, except in this simple implementation there's only a single location for a value to be looked up from. Here's how we'll do it: let state_get : store state = fun s -> (s, s) This passes through the current store unaltered, and also returns a copy of the store as its payload. (What exactly corresponds to this is the simpler Reader operation `ask`.) We can use the `state_get` operation like this: some_existing_state_monad_value >>= fun _ -> state_get >>= (fun cur_store -> ...) The `fun _ ->` part here discards the payload wrapped by `some_existing_state_monad_value`. We're only going to pass through, unaltered, whatever *store* is generated by that monadic box. We also wrap that store as *our own payload*, which can be retrieved by further operations in the `... >>= ...` chain, such as `(fun cur_store -> ...)`. As we've mentioned elsewhere, `xx >>= fun _ -> yy` can be abbreviated as `xx >> yy`. The other operation for the State monad will be to update the existing store to a new one. This operation looks like this: let state_put (new_store : int) : dummy state = fun s -> (dummy, new_store) If we want to stick this in a `... >>= ...` chain, we'll need to prefix it with `fun _ ->` too, like this: some_existing_state_monad_value >>= fun _ -> state_put 100 >>= ... Or: some_existing_state_monad_value >> state_put 100 >>= ... In this usage, we don't care what payload is wrapped by `some_existing_state_monad_value`. We don't even care what store it generates, since we're going to replace that store with our own new store. A more complex kind of `state_put` operation might insert not just some constant value as the new store, but rather the result of applying some function to the existing store. For example, we might want to increment the current store. Here's how we could do that:
```some_existing_state_monad_value >> state_get >>= (fun cur_store -> state_put (succ cur_store)) >>= ...
```