F# Scribbles

My experiments with F#

Copying or modifying immutable nested record

This is just a simple code snippet to show case how to copy or modify a immutable nested record type.

Let us define a nested type

1
2
3
4
type Address = {no: int; street: string; city: string; zip: string}

type Profile = {name: string; address: Address}
                 member this.tos() = sprintf "%s. %d - %s, %s %s" this.name this.address.no this.address.street this.address.city this.address.zip

The Profile contains Address type. Let us create an instance.

1
let profile = {name = "Sheik"; address = {no = 1; street = "Road"; city = "Chennai"; zip = "600001"}}

If you want to change the street name alone for profile

1
let mprofile = {profile with address = {profile.address with street = "Nungambakkam High Road"}}

The result will be

1
2
3
4
5
> profile.tos()
val it : string = "Sheik. 1 - Road, Chennai 600001"

> mprofile.tos()
val it : string = "Sheik. 1 - Nungambakkam High Road, Chennai 600001"