Search code examples
smlsmlnj

SML/NJ - about ":=" operator


I did some checks on := operator and I want to make sure that I got it well .

let -

val r1 = ref 1 ;  (* !r1 = 1 *)
val r2 = ref 2 ;  (* !r2 = 2 *)
val r3 = ref 3 ;  (* !r3 = 3 *)

r1 := !r2 ; (* !r1 = 2 *)
r2 := !r3 ; (* !r2 = 3 *)
!r1 ;  (* still !r1 = 2 *)

Apparently I thought that r2 := !r3 ; would cause to !r1 value to change too , which didn't occurred , so it seems that r1 := !r2 ; does not points r1 to same address as r2 ,but just allocate new memory for !r1 and set the 2 value there .

Am I right ?


Solution

  • Assignment does not allocate new memory. After r1 := !r2, the reference r1 "points" to the value 2 taken from r2, not to r2 itself. Consequently, updating r2 later does not affect it.

    If you want such an effect, then you have to use another indirection, e.g. an int ref ref type.