Deepcopy: Difference between revisions

Content added Content deleted
(→‎{{header|Rust}}: Added Rust)
Line 1,052: Line 1,052:
{bar => [0 2], foo => 0}
{bar => [0 2], foo => 0}
{bar => [0 1], foo => 0}
{bar => [0 1], foo => 0}
</pre>

=={{header|Phix}}==
Handled natively. Phix uses reference counting with copy-on-write semantics; the initial copy is fast even for huge complex and deeply nested structures (copying a single machine-word-sized reference and incrementing a single machine-word-sized reference count), and when a shared object (anything with a refcount>1) is modified, an internal clone of just one affected level occurs, with all the rest of the structure remaining shared (but obviously still properly protected in the same way).
<lang Phix>object a, b
a = {1,{2,3},"four",{5.6,7.{8.9}}}
b = a
b[3] = 4
?a
?b</lang>
{{out}}
<pre>
{1,{2,3},"four",{5.6,7,{8.9}}}
{1,{2,3},4,{5.6,7,{8.9}}}
</pre>
It is worth noting that this mechanism is also used for parameter passing, and when a local variable is both passed as a parameter and assigned on return, automatic pass-by-reference handling kicks in to avoid any unnecessary internal cloning.

Should you for some (probably misguided) reason really want it, a recursive clone function might look like this:
<lang Phix>function deep_copy(object o)
object res
if atom(o) then
res = o
else
res = repeat(' ',length(o))
for i=1 to length(o) do
res[i] = deep_copy(o[i])
end for
end if
return res
end function

object c = deep_copy(b)
?c</lang>
Or you could just serialize and deserialize:
<lang Phix>include builtins\serialize.e
object d = deserialize(serialize(a))
?d</lang>
{{out}}
<pre>
{1,{2,3},4,{5.6,7,{8.9}}}
{1,{2,3},"four",{5.6,7,{8.9}}}
</pre>
</pre>