Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to define a large immutable type with pieces that get updated?

Tags:

f#

I'm designing a game object in F#. In C++, I would make classes to represent the graphical aspect, physical etc each with dynamic values, and then add instances of those classes to a GameObject. I could use the same design in F# with mutable types, but I'm trying to keep everything immutable. So if I used the same design I would be recreating thousands of large objects each frame, and probably spend all cpu time just allocating.

Is there some way I can define a type where I could link to another object's values and supply new ones, to cut down on allocations?

Eg to change the colour of a box, I want to use the old box's memory with a new graphics piece, and use the old graphics piece's memory with a new colour:

let box = ...
...

let changedBox = {box with 
                 graphics = { box.graphics with colour = blue} }
like image 972
Patrick Avatar asked Jul 26 '10 21:07

Patrick


1 Answers

Yes, exactly. Assuming that "the big object" is in fact a reference graph of many smaller objects, then the typical "update of an immutable" just creates one or two new small objects and references the same old ones for the rest.

For example, if Person has a Name and Address, and Address has a Street and City and State and Zip, and I need to update the zip of a person, then I only need to create new objects for the spanning tree from the root to the Zip. See e.g. the red-black color diagrams in this blog. In the person example, the Name, Street, City, and State objects would be reused, but the ZIp would be a new object, and the Address would be a new object (since it contains the new Zip), and the Person would be a new object (since it contains the new Address). Does it make sense?

like image 121
Brian Avatar answered Sep 24 '22 02:09

Brian