I want to have the advantage of functional data structures (multiple versions of data that can share structure) but be able to modify it in an imperative style.
What I'm thinking about (and a possible use): a RPG game in which whole game history is stored (for example, to allow for travelling back in time). Using copy-on-write, I could simply clone the structure holding game state and modify it by introducing a new turn - but have access to the earlier turns (not necessarily all of them, maybe just selected snapshots of game state), without the penalty of having to copy everything every time.
Let's say foo
is a map.
bar = foo.clone()
Nothing of foo
's structure (for example, tree) gets copied yet. However,
from now on bar
is treated as a copy and no changes are allowed to propagate
back to `foo'.
baz = bar[someKey]
baz.modifyInSomeWay()
Now
- a new object gets created, that is a modified copy of
baz
. bar
is replaced with a new map, holding newbaz
(possibly retaining some offoo
's structure).foo
is unaffected.
But if we then do...
baz.modifyAgain()
...baz
can be just modified, because we have a recent version of it. bar
doesn't need to be changed.
All this requires holding some version information about foo
and bar
,
increasing it on foo.clone()
, and passing it to baz
somehow (by making it
a proxy object?).
Also, any part of structure that has been cloned becomes a 'part of history' and can't be changed anymore, which could be enforced at run-time.
This resembles JavaScript's prototypes a bit, but I it's more as it allows for changes to propagate upwards. I think it would be something like a version control system.
- Has this been done, and to what extent?
- Is this a good idea? If not, is there a way to save it?
- How could it be implemented? I was thinking about building it on top of some high-level GC-ed language, like Python.