Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutable record fields and { x with ... }

I've been reading through the ocaml docs but I can't the part that explains how { x with ... } works around mutable fields. The closest I've found says

6.7 Expressions

expr := ...
    ∣ { expr with  field =  expr  { ; field =  expr }  [;] }

...

Records

The expression { expr with field1 = expr1 ; … ; fieldn = exprn } builds a fresh record with fields field1 … fieldn equal to expr1 … exprn, and all other fields having the same value as in the record expr. In other terms, it returns a shallow copy of the record expr, except for the fields field1 … fieldn, which are initialized to expr1 … exprn.

That "shallow copy" verbiage could be interpreted to mean that mutable fields not mentioned share storage space or could refer to nested records. When I test (using "The OCaml toplevel, version 4.00.1") thus

type t = { mutable x : int; mutable y: int }
let a = {x=42;y=123}
let b = { a with y=124}
let _ = a.x <- 43
let _ = Printf.printf "b.x=%d\n" b.x
;;

I get a result which indicates that b.x does not alias a.x:

b.x=42
type t = { mutable x : int; mutable y : int; }
val a : t = {x = 43; y = 123}
val b : t = {x = 42; y = 124}

which makes me very happy but I want to make sure that

{ e with fi=x }

is effectively syntactic sugar for something like

(let tmp=e in { f0=tmp.f0; … fi-1=tmp.fi-1; fi=x; fi+1=tmp.fi+1; …; fn=tmp.fn })

and that mutable fields cannot be backed by a ref that an implementation could reuse instead of allocating new mutable storage.

like image 714
Mike Samuel Avatar asked Oct 22 '22 03:10

Mike Samuel


1 Answers

Everywhere I've seen, "shallow copy" means, simply transfer all the components over as if by assignment, even in languages where all fields are always mutable, like Java. So in this case (let tmp=e in { f0=tmp.f0; … fi-1=tmp.fi-1; fi=x; fi+1=tmp.fi+1; …; fn=tmp.fn }) is exactly what it should mean.

like image 107
newacct Avatar answered Nov 15 '22 06:11

newacct