I was wondering if in F# there is some sugar for cloning a class instance changing just one or a few of the properties.
I know in F# it is possible with records:
let p2 = {p1 with Y = 0.0}
Another option is to wrap a record in a class. Some thing like
type PersonState = { FirstName : string; LastName : string; }
type Person private (state : PersonState) =
new (firstName, lastName) =
Person({ FirstName = firstName; LastName = lastName })
member this.WithFirstName value =
Person { state with FirstName = value }
member this.WithLastName value =
Person { state with LastName = value }
member this.FirstName with get () = state.FirstName
member this.LastName with get () = state.LastName
Use as
let JohnDoe = Person("John", "Doe")
let JaneDoe = JohnDoe.WithFirstName "Jane"
let JaneLastName = JaneDoe.LastName
This approach avoids explicit cloning and mutability.
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