Deepcopy: Difference between revisions

Add Factor
No edit summary
(Add Factor)
Line 455:
[[1|2]],
[],[],[],[]}}}
</pre>
 
=={{header|Factor}}==
It's possible to create deep copies with <code>[ clone ] deep-map</code>, though this suffers from the limitation that it will hang indefinitely on circularities. We can even do this with tuples, since named tuples allow tuples to be treated like arrays. The following is a demonstration of deep copying an object in this manner.
{{works with|Factor|0.99 2019-10-06}}
<lang factor>USING: accessors arrays io kernel named-tuples prettyprint
sequences sequences.deep ;
 
! Define a simple class
TUPLE: foo bar baz ;
 
! Allow instances of foo to be modified like an array
INSTANCE: foo named-tuple
 
! Create a foo object composed of mutable objects
V{ 1 2 3 } V{ 4 5 6 } [ clone ] bi@ foo boa
 
! create a copy of the reference to the object
dup
 
! create a deep copy from this copy
>array [ clone ] deep-map T{ foo } like
 
! print them both
"Before modification:" print [ [ . ] bi@ ] 2keep nl
 
! modify the deep copy
[ -1 suffix! ] change-bar
 
! print them both again
"After modification:" print [ . ] bi@</lang>
{{out}}
<pre>
Before modification:
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
 
After modification:
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
T{ foo { bar V{ 1 2 3 -1 } } { baz V{ 4 5 6 } } }
</pre>
 
Another way to make deep copies is by serializing an object to a byte array and then deserializing it back to an object. This has the advantage of preserving circularities, but it doesn't work on non-serializable objects (such as continuations).
<lang factor>! Create a foo object composed of mutable objects
V{ 1 2 3 } V{ 4 5 6 } [ clone ] bi@ foo boa
 
! create a copy of the reference to the object
dup
 
! create a deep copy from this copy
object>bytes bytes>object
 
! print them both
"Before modification:" print [ [ . ] bi@ ] 2keep nl
 
! modify the deep copy
[ -99 suffix! ] change-bar
 
"After modification:" print [ . ] bi@</lang>
{{out}}
<pre>
Before modification:
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
 
After modification:
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
T{ foo { bar V{ 1 2 3 -99 } } { baz V{ 4 5 6 } } }
</pre>
 
1,808

edits