Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clone

f#

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}
like image 727
NoIdeaHowToFixThis Avatar asked Nov 21 '13 09:11

NoIdeaHowToFixThis


1 Answers

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.

like image 111
hocho Avatar answered Oct 19 '22 18:10

hocho