ML standard: reference cell confusion

I am reading Harper Intro for SML and am a bit confused in control cells. On page 114, he gives the following example:

val r = ref 0 val s = ref 0 val _ = r := 3 val x = !s + !r val t = r val _ = t := 5 val y = !s + !r val z = !t !r 

"After completing these bindings, x is tied to 3, y is tied to 5, and z is tied to 10.

Here is my trace of his code:

 val r = ref 0 //allocates storage for r and sets to 0 val s = ref 0 //allocates storage for s and sets to 0 val _ = r := 3 //sets r = 3 val x = !s + !r //sets x = 0 + 3 = 3 val t = r //sets t = 3 val _ = t := 5 //sets t = 5 val y = !s + !r //sets y = 0 + 3 = 3 val z = !t !r //sets z = 5 + 3 = 8 

My x is correct (3), but my y and z are both wrong (my y is 3 instead of 5, and my z is 5 instead of 10).

Where am I wrong here?

Also, why is val _ = t := 5 necessary instead of the simple t := 5 ?

Thanks bclayman

+5
source share
2 answers

val t = r does not set t to 3. It sets t as the same reference cell as r .

Thus, when you do t := 5 , you set both the contents of t and r to 5, since both contain the same reference cell.

As for your other question, t := 5 is the function call of the function := : 'a ref * 'a -> unit . So t := 5 is an expression that evaluates to () .

val _ = t := 5 just discards () and turns it into an declaration, not an expression.

+5
source

val t = r makes t an alias for r. They both belong to the same place in the store. Thus, t := 5 has the side effect of changing the contents of the memory cell, which r also refers to (since t and r belong to the same place). Consequently

 val y = !s + !t 

sets y = 0 + 5 = 5.

You are correct that val _ = t := 5 basically matches t := 5 , although the former suppresses the output in REPL (by discarding the value of the assignment expression).

+3
source

All Articles