Deep Clone
Tuesday, May 28, 2024
Someone on the Factor Discord server asked if we have an existing word in Factor to deep clone an object. Specifically, a word that will recursively descend an object’s tree, cloning every visited object to make sure that no reference remains in common between the deep clone and the original.
The answer is: not exactly.
In particular, we have had a
clone word that
creates a practical shallow clone of an object using the (clone)
primitive word – which generates a “byte-by-byte copy of the given object” –
and sometimes makes sure to additionally clone certain slots for separate
mutation of the cloned object.
But, we also have a serialize vocabulary that could be used (or abused?) to serialize an object and then deserialize it as a kind of poor man’s deep clone:
: deep-clone ( object -- object' )
object>bytes bytes>object ;
This works, and supports the deep cloning of most objects. There are still a few edge cases that are not a full clone, for example:
- The
f
object is a singleton, and is the deep clone of itself. - Words are not deep cloned, but return as references to themselves.
- Integers that are
fixnum
return as themselves. - Continuations are not supported.
But, other than that, it is a very practical deep clone. And, because it transitions through a byte-array, in some ways is more defensive against errors introduced by a type-specific deep-clone vocabulary, at the cost of some space/time tradeoff. Some future discussion is taking place on what a deeper clone might look like, but this is quite useful as-is.
This is available in the latest development version.