liveBook · Manning

Copy-and-update syntax

As explained in F# in Action: A Revised Edition of Get Programming with F#

Copy-and-update syntax is F# syntax that creates a record value by copying fields from an existing record and overriding or adding fields.

F# record fields are immutable by default, so changing an address does not mean assigning to its existing fields. Copy-and-update syntax creates a new record from an existing one, replacing only the fields you specify. The original value remains unchanged. section 5.3.2

Update an address

let addressInDE = { theAddress with Town = "Berlin" Country = "DE" } The new address takes its other fields from theAddress. Writing out every field again would be unnecessary; assigning to theAddress.Town would instead attempt to mutate an immutable field. section 5.3.2

Anonymous records extend the pattern: one copy-and-update expression can replace existing fields and add new ones. That makes it useful when an inline data shape needs extra fields. section 5.4.1

let companyWithBankDetails =
    {|
        company with
            AccountNumber = 123
            SortCode = 456
    |}

The anonymous-record expression copies company and adds AccountNumber and SortCode. section 5.4.1

Prefer immutable updates first. Records can have mutable fields when necessary, but measure a performance problem before changing the record definition for that reason. section 5.3.2

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Works through a two-field record update and shows anonymous-record field additions, without detailing compiler internals.
Examples
Shows an address copied with a new town and country, plus an anonymous record given bank-detail fields.
What it assumes
Assumes basic record creation and field access; introduces immutable updating directly.
What you can do after
Practice/perform immutable record updates and add fields when copying anonymous records.
How it connects
Connects immutable records, anonymous records, type inference, and mutable fields.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.