views:

48

answers:

1

Hi Guys,

I have a very basic question regarding OCaml records. Suppose I have a record defined:

type r = {a:int;b:int;c:int}
let x = {a=3;b=8;c=2}

Now, suppose I want to create a new record which has all fields equal to x but which has c=4. I could write:

let y = {a=3;b=8;c=4}

but this is annoying because there's not need to re-write a=3 and b=8. I could also write:

let y = {a=x.a;b=x.b;c=4}

but this is still not good if the record has many fields. Is there any way of writing something like:

let y = {x with c=4}

or something of the sort?

Thanks a lot for any help.

All the best, Surikator.

+8  A: 

yeah, and that's the exact syntax.

let y = {x with c=4}
nlucaroni
Lol... How about that?! Great stuff. Thanks!
Surikator
Yeah, pretty impressive intuition you have there.
nlucaroni
For a given type definition, `{x with c=4}` is equivalent to `{a=x.a;b=x.b;c=4}`. However, if you change the record type to add or remove a field, the compiler will not warn you about the former, which may be exactly what you want or not what you want. This is how you should choose between the two notations.
Pascal Cuoq
@Pascal; I agree. I've had a bug derived from that. It doesn't happen very often in my experience, but over a long enough time line it will surely snag you.
nlucaroni