Mutation Via References

Posted by Beetle B. on Sat 13 August 2016
val x = ref 42
val y = ref 42
(* Although the number is the same, x and y do NOT
point to the same thing! *)
val z = x (* z is now a reference to 42 *)
val _ = x := 43
val w = (!y) + (!z) (* 85 *)

Generally, ref e is a reference to the result of evaluating e.

e1:=e2: Update the contents of whatever reference e1 evaluates to the result of e2.

!e retrieves the value of the reference that e evaluates to.

Note that x above will always point to the same object. We can change the value in the object, but cannot make x point to something else.