Essentials of Programming Languages -- 4 State
4.1 Computational Effects
The value produced by a computation may have effects as well: it may read,print,or alter the state of memory or a file system.
What's the difference between producing a value and producing an effect?
- An effect is global: it is seen by the entire computation.
- An effect affects the entire computation(pun intended).
We will be concerned primarily with a single effect: assignment to a location in memory.
How does assignment differ from binding?
binding is local, but variable assignments is potentially global. It is about the sharing of values between otherwise unrelated portions of the computation.
eg: Two procedures can share information if the both know about the same location in memory;
A single procedure can share information with a future invocation of itself by leaving the information in a known location.
A data structure that represents a location is called reference.
- A location is a place in memory where a value can be stored
- A reference is a data structure that refers to that place
Reference are sometimes called L-values.
We consider two designs for a language with a store. We call these designs explicit references and implicit references.
4.2 EXPLICIT-REFS: A Language with Explicit References
ExpVal = Int + Bool + Proc + Ref(ExpVal)
DenVal = ExpVal
Interfaces:
newref: allocates a new location and returns a reference to it.deref: dereferences a reference: that is, it returns the contents of the location that the reference represents.setref: changes the contents of the location that the reference represents.
The usage of reference:
let x = newref(0)
in letrec even(dummmy)
= if zero?(deref(x))
then 1
else begin
setref(x, -(deref(x),1));
(odd 888)
end
odd(dummy)
= if zero?(deref(x))
then 0
else begin
setref(x, -(deref(x), 1));
(even 888)
end
in begin setref(x, 13); odd(888) end
even and odd communicate not by passing data explicitly, but by changing the contents of the variable they share.
the call argument "888" is dummy.
Another use of assignment is to create hidden state through the use of private variables. Here is an example:
let g = let counter = newref(0)
in proc (dummy)
begin
setref(counter, -(deref(counter), -1))
deref(counter)
end
in let a = (g 11)
in let b = (g 11)
in -(a, b)
Here is a picture of the environment in which g is bound.

4.2.1 Store-Passing Specifications
In our language, any expression may have an effect. To specify these effects, we need to describe what store should
be used for each evaluation and how each evaluaion can modify the store.
浙公网安备 33010602011771号