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 withfields field1 … fieldn
equal toexpr1 … exprn
, and all other fields having the same value as in the recordexpr
. In other terms, it returns a shallow copy of the recordexpr
, except for the fieldsfield1 … fieldn
, which are initialized toexpr1 … 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With