URL87
URL87

Reputation: 11012

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 ?

Upvotes: 0

Views: 674

Answers (2)

newacct
newacct

Reputation: 122429

Yes. r1 and r2 were initialized to point to different data structures. The := operator simply changes the value of the ref structure pointed to by the left side. If you want r1 and r2 to point to the same ref structure, you could have not defined r1 initially, and then later defined it like val r1 = r2. It is impossible to assign to a variable in ML after it is initially defined.

Upvotes: 0

Andreas Rossberg
Andreas Rossberg

Reputation: 36088

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.

Upvotes: 4

Related Questions