Clone a class instance, changing just a few of the properties

clone, f#

Solution

One way to simulate copy-and-update expressions for classes is with a copy constructor taking optional args.

type Person(first, last, age) =
  new (prototype: Person, ?first, ?last, ?age) =
    Person(defaultArg first prototype.First, 
           defaultArg last prototype.Last, 
           defaultArg age prototype.Age)
  member val First = first
  member val Last = last
  member val Age = age

let john = Person("John", "Doe", 45)
let jane = Person(john, first="Jane")

EDIT

You didn't ask for this, but in many cases making the class mutable results in clearer code:

type Person(first, last, age) =
  member val First = first with get, set
  member val Last = last with get, set
  member val Age = age with get, set
  member this.Clone() = this.MemberwiseClone() :?> Person

let john = Person("John", "Doe", 45)
let jane = john.Clone() in jane.First <- "Jane"

Problem

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} ```

Original source