Deepcopy: Difference between revisions

m
sytnax highlighting fixup automation
m (sytnax highlighting fixup automation)
Line 22:
=={{header|6502 Assembly}}==
Deep copying is very simple on the 6502 - just load a value from memory and store it somewhere else.
<langsyntaxhighlight lang="6502asm">LDA $00 ;read the byte at memory address $00
STA $20 ;store it at memory address $20</langsyntaxhighlight>
 
Now, anything you do to the byte at <tt>$00</tt> won't affect the byte at <tt>$20</tt>.
<langsyntaxhighlight lang="6502asm">LDA $00 ;read the byte at memory address $00
STA $20 ;store it at memory address $20
INC $00 ;add 1 to the original
CMP $00 ;compare the copy to the original (we could have done LDA $20 first but they're the same value so why bother)
BNE notEqual ;this branch will be taken.</langsyntaxhighlight>
 
There is no built-in <code>memcpy()</code> function but it doesn't take much effort to create one. This version can copy up to 256 bytes of memory:
<langsyntaxhighlight lang="6502asm">;input:
;$00,$01 = pointer to source
;$07,$08 = pointer to destination
Line 46:
dex
bne memcpy_again
rts</langsyntaxhighlight>
 
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">list L1, L2;
 
# Lists are heterogeneous:
Line 81:
o_text(l_query(l_query(L2, 2), 1));
o_text(l_query(l_query(L1, 2), 1));
o_byte('\n');</langsyntaxhighlight>
{{out}}
<pre>deepcopy
Line 88:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">x: #[
name: "John"
surname: "Doe"
Line 111:
 
print ["Name of first person:" x\name]
print ["Name of second person:" y\name]</langsyntaxhighlight>
 
{{out}}
Line 122:
{{works with|AutoHotkey L}}
http://www.autohotkey.com/board/topic/85201-array-deep-copy-treeview-viewer-and-more/
<langsyntaxhighlight lang="autohotkey">DeepCopy(Array, Objs=0)
{
If !Objs
Line 134:
: DeepCopy(Val,Objs) ; Otherwise, clone this sub-array
Return Obj
}</langsyntaxhighlight>
 
=={{header|AWK}}==
AWK's only data structure is the associative array, and it doesn't allow nested associative arrays (POSIX). Thus:
<langsyntaxhighlight lang="awk">BEGIN {
for (elem in original)
copied[elem] = original[elem]
}</langsyntaxhighlight>
 
=={{header|Babel}}==
Line 149:
Here is an example of shallow-copy - modifying one object modifies both because they are really just references to one underlying object:
 
<langsyntaxhighlight lang="babel">babel> [1 2 3] dup dup 0 7 0 1 move sd !
---TOS---
[val 0x7 0x2 0x3 ]
[val 0x7 0x2 0x3 ]
---BOS---</langsyntaxhighlight>
 
Deep-copy is proved by the ability to separately modify two objects:
 
<langsyntaxhighlight lang="babel">babel> clear [1 2 3] dup cp dup 0 7 0 1 move sd !
---TOS---
[val 0x7 0x2 0x3 ]
[val 0x1 0x2 0x3 ]
---BOS---</langsyntaxhighlight>
 
You can deep-copy any pure-Babel object with cp. Here is a list-of-lists, we copy it using cp:
 
<langsyntaxhighlight lang="babel">babel> ((1 2) (3 4) (5 6)) cp
babel> {lsnum !} each
( 1 2 )
( 3 4 )
( 5 6 )</langsyntaxhighlight>
 
Here is a list-of-maps, we copy it using cp:
 
<langsyntaxhighlight lang="babel">babel> ([map "foo" 3 "bar" 17] [map "foo" 4 "bar" 18] [map "foo" 5 "bar" 19] [map "foo" 0 "bar" 20]) cp
babel> 2 ith "bar" lumap ! itod say !
19</langsyntaxhighlight>
 
Here is Babel code, we copy it using cp:
 
<langsyntaxhighlight lang="babel">babel> { { 1 randlf 100 rem itod << " " << } 20 times } cp
babel> eval
86 51 50 43 82 76 13 78 33 45 11 35 84 25 80 36 33 81 43 24</langsyntaxhighlight>
 
=={{header|C}}==
===Structures without pointers===
Structures without pointers can be copied like ''standard'' C variables such as int, float, char etc. The level of nesting is irrelevant. As the following implementation shows, a simple assignment is enough :
<syntaxhighlight lang="c">
<lang C>
#include<stdio.h>
 
Line 234:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 252:
===Structures with pointers===
Structures with pointers which are usually used to represent data structures such as Linked lists, Stacks, Trees, Graphs etc. have to be copied element by element. A simple assignment as in the above example will not be a copy at all. It will be two pointers pointing towards the same memory location.
<syntaxhighlight lang="c">
<lang C>
#include<stdlib.h>
#include<stdio.h>
Line 343:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 351:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
namespace prog
Line 378:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 387:
any pointers.
 
<langsyntaxhighlight lang="cpp">
#include <array>
#include <iostream>
Line 416:
std::cout << mapCopy[3][0][1] << "\n";
std::cout << mapCopy[7][1][2] << "\n";
}</langsyntaxhighlight>
{{out}}
<pre>the original values:
Line 438:
For instance <code>#42=(a b)</code> denotes the list <code>(a b)</code> and furthermore, it associates it with the number 42. Then, later in the same form, #42# denotes an additional occurence of the same <code>(a b)</code> object. So for instance, a cons cell whose <code>car</code> is 1, and whose <code>cdr</code> points back to that cons cell is written <code>#1=(1 . #1#)</code>.
 
<langsyntaxhighlight lang="lisp">$ clisp -q
[1]> (setf *print-circle* t)
T
Line 444:
#1=(1 . #1#)
[3]> (read-from-string "#1=(1 . #1#)") ;; read it from a string
#1=(1 . #1#) ;; a similar circular list is returned</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">local :(copy-action) {}
 
(copy-action)!list obj cache:
Line 498:
 
!. C
!. D</langsyntaxhighlight>
{{out}}
<pre>{ :foo [ "bar" ] [ ] [ & 1 2 & 3 4 ] }
Line 510:
=={{header|Delphi}}==
{{libheader| System.TypInfo}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program DeepCopyApp;
 
Line 561:
Writeln(b.value4);
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>Value of "a":
Line 579:
In E, serialization is generalized to transforming object graphs from one representation to another. Deep copying, therefore, consists of transforming a live object graph into a live object graph, by connecting <code>deSubgraphKit</code>'s output to its input. No intermediate serialized form is needed.
 
<langsyntaxhighlight lang="e">def deSubgraphKit := <elib:serial.deSubgraphKit>
def deepcopy(x) {
return deSubgraphKit.recognize(x, deSubgraphKit.makeBuilder())
}</langsyntaxhighlight>
 
As befits a serialization system, this deep copy may operate on any serializable structure, whether standard or user-defined, and the structure may contain cycles.
 
<langsyntaxhighlight lang="e">? def x := ["a" => 1, "b" => [x].diverge()]
# value: ["a" => 1, "b" => [<***CYCLE***>].diverge()]
 
Line 607:
 
? x["b"][0] == x
# value: true</langsyntaxhighlight>
 
(<code>.diverge()</code> produces mutable data structures, and <code>&lt;***CYCLE***></code> is what is printed when printing some object meets itself again.)
Line 646:
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}}
<langsyntaxhighlight lang="factor">USING: accessors arrays io kernel named-tuples prettyprint
sequences sequences.deep ;
 
Line 671:
 
! print them both again
"After modification:" print [ . ] bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 684:
 
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).
<langsyntaxhighlight lang="factor">! Create a foo object composed of mutable objects
V{ 1 2 3 } V{ 4 5 6 } [ clone ] bi@ foo boa
 
Line 699:
[ -99 suffix! ] change-bar
 
"After modification:" print [ . ] bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 714:
=={{header|FreeBASIC}}==
{{trans|PureBasic}}
<langsyntaxhighlight lang="freebasic">
Type DeepCopy
value1 As Integer
Line 753:
End With
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 776:
 
'''Heterogeneous:'''
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 812:
fmt.Println(c1) // show changes
fmt.Println(c2) // show copy unaffected
}</langsyntaxhighlight>
Output:
<pre>
Line 823:
 
DIY here requires you to code a traversal algorithm.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 882:
fmt.Println("original:")
c.list()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 900:
 
If you still want a generalized deep copy, one can be cobbled with an os.Pipe and the gob package, which does type safe serialization. The deepcopy function shown below works on arbitrary data with a few limitations. It handles data types with recursive or cyclic definitions, but does not handle cycles in the data itself. For example, it handles a linked list, but not a ring data structure. Another limitation is that struct fields must be exported. (That is, fields must start with an upper case letter. This makes the field visible outside the package.)
<langsyntaxhighlight lang="go">package main
 
import (
Line 961:
// show that copy is unaffected
fmt.Println(l2)
}</langsyntaxhighlight>
Output:
<pre>
Line 976:
The code requires modification to run under Icon as Unicon extended key(X) to operate on lists and records not just tables.
 
<langsyntaxhighlight Uniconlang="unicon">procedure deepcopy(A, cache) #: return a deepcopy of A
local k
 
Line 999:
}
return .cache[A]
end</langsyntaxhighlight>
 
The following code demonstrates deepcopy usage and that the resulting structure is different from the original by comparing assignment, copy, and deepcopy.
 
<langsyntaxhighlight Iconlang="icon">link printf,ximage
 
procedure main()
Line 1,056:
procedure showequiv(x,y) #: show (non-)equivalence of two values
return printf(" %i %s %i\n",x,if x === y then "===" else "~===",y)
end</langsyntaxhighlight>
 
{{libheader|Unicon Code Library}}
Line 1,118:
J uses pass by value semantics (typically implemented as copy on write) so Deepcopy is trivial -- values inside the language are immutable.
 
<langsyntaxhighlight lang="j"> a=:b=: 2 2 2 2 2 NB. two copies of the same array
b=: 3 (2)} b NB. modify one of the arrays
b
2 2 3 2 2
a
2 2 2 2 2</langsyntaxhighlight>
 
That said, J can reference values outside the language. But Deepcopy of those values is, by definition, outside the scope of the language. Usually, bringing the values into the language is sufficient.
Line 1,139:
 
Copy constructor, object serialization, and object clone are demonstrated below.
<langsyntaxhighlight lang="java">
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
Line 1,299:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,334:
=={{header|JavaScript}}==
You can use JSON for ordinary objects.
<syntaxhighlight lang="javascript">
<lang JavaScript>
var deepcopy = function(o){
return JSON.parse(JSON.stringify(src));
Line 1,343:
var dst = deepcopy(src);
print(JSON.stringify(src));
</syntaxhighlight>
</lang>
You can go further if you have <code>uneval()</code>. You can even deep copy objects with cyclic references.
<syntaxhighlight lang="javascript">
<lang JavaScript>
var deepcopy = function(o){
return eval(uneval(o));
Line 1,354:
var dst = deepcopy(src);
print(uneval(src));
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 1,376:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6.0
 
cp = deepcopy(obj)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
Line 1,388:
 
The serialization approach is used below.
<langsyntaxhighlight lang="scala">// Version 1.2.31
 
import java.io.Serializable
Line 1,458:
p3 = deepCopy(p1)
printDetails(p1, null, p3!!, null)
}</langsyntaxhighlight>
 
{{out}}
Line 1,489:
Every Lasso type has an ascopy and ascopydeep method.
 
<langsyntaxhighlight Lassolang="lasso">local(copy) = #myobject->ascopydeep</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- Supports lists, property lists, images, script instances and scalar values (integer, float, string, symbol).
on deepcopy (var, cycleCheck)
case ilk(var) of
Line 1,510:
return var
end case
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">val = [#foo:42, "bar":[1,2,3, "Hello world!"]]
put deepcopy(val)
-- [#foo: 42, "bar": [1, 2, 3, "Hello world!"]]
Line 1,518:
val.foo = 42
val.bar = [1, 2, 3, "Hello world!"]]
copy = deepcopy(val)</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 1,527:
===Recursive===
 
<langsyntaxhighlight Lualang="lua">function _deepcopy(o, tables)
if type(o) ~= 'table' then
Line 1,551:
function deepcopy(o)
return _deepcopy(o, {})
end</langsyntaxhighlight>
 
{{out}}
Line 1,618:
====Breadth-first====
 
<langsyntaxhighlight Lualang="lua">function deepcopy(o, mode)
 
if type(o) ~= 'table' then
Line 1,655:
 
return new_t
end</langsyntaxhighlight>
 
<pre>> q = {}
Line 1,685:
is copied. Then, the context is restored and copying of the parent table continues.
 
<langsyntaxhighlight Lualang="lua">function deepcopy(o, mode)
 
if type(o) ~= 'table' then
Line 1,774:
 
return tables[o] -- return the copy corresponding to the root table `o`
end</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Everything in Mathematica is a value type.
<langsyntaxhighlight Mathematicalang="mathematica">a = {"foo", \[Pi], {<|
"deep" -> {# +
1 &, {{"Mathematica"}, {{"is"}, {"a"}}, {{{"cool"}}}, \
Line 1,786:
a[[3, 1, 1, 1]] = #^2 &;
Print[a];
Print[b];</langsyntaxhighlight>
{{out}}
<pre>{foo, -3 + π, {<|deep -> {#1^2 &, {{Mathematica}, {{is}, {a}}, {{{cool}}}, {{programming}, {language!}}}}|>}}
Line 1,793:
=={{header|Nim}}==
Works with Nim 1.4.0:
<syntaxhighlight lang ="nim">deepCopy(newObj, obj)</langsyntaxhighlight>
For example with binary trees:
<langsyntaxhighlight lang="nim">type
Node[T] = ref TNode[T]
TNode[T] = object
Line 1,828:
 
echo "Tree:"
echo preorder tree</langsyntaxhighlight>
Output:
<pre>Tree2:
Line 1,839:
This code is just provided in order to achieve this task, but an OCaml programmer wouldn't use this kind of code, because this <code>copy</code> function is made generic due to the use of the [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Obj.html <code>Obj</code>] module, and it is not recommanded to use it.
 
<langsyntaxhighlight lang="ocaml">let rec copy t =
if Obj.is_int t then t else
let tag = Obj.tag t in
Line 1,854:
end else failwith "copy" ;;
 
let copy (v : 'a) : 'a = Obj.obj (copy (Obj.repr v))</langsyntaxhighlight>
 
OCaml programmers will prefer to use specialised copy functions for each mutable types. For base types like strings and arrays, the standard library provides copy functions: <code>String.copy</code> and <code>Array.copy</code>. For mutable user-defined data structures, we will create a copy function based on these previous copy functions. For example in the module [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Hashtbl.html <code>Hashtbl</code>], the type is a record containing an integer and an array, so the copy function is defined as below:
<langsyntaxhighlight lang="ocaml">let copy h =
{ size = h.size;
data = Array.copy h.data }</langsyntaxhighlight>
 
=={{header|OxygenBasic}}==
<syntaxhighlight lang="text">
'DEEP COPY FOR A RECURSIVE TREE STRUCTURE
 
Line 1,926:
del bc
del br
</syntaxhighlight>
</lang>
 
 
Line 1,938:
use [http://search.cpan.org/perldoc?Storable Storable]; <code>Storable::dclone()</code> is exactly what you are looking for.
 
<syntaxhighlight lang="perl">
<lang Perl>
#!/usr/bin/perl
use strict;
Line 1,950:
print Dumper($src);
print Dumper($dst);
</syntaxhighlight>
</lang>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
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 the minimum necessary levels occurs, with all the rest of the structure remaining shared, but obviously still properly protected in the same way.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #004080;">object</span> <span style="color: #000000;">a<span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span>
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">2<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">}<span style="color: #0000FF;">,<span style="color: #008000;">"four"<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">5.6<span style="color: #0000FF;">,<span style="color: #000000;">7<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">8.9<span style="color: #0000FF;">}<span style="color: #0000FF;">}<span style="color: #0000FF;">}</span>
Line 1,962:
<span style="color: #0000FF;">?<span style="color: #000000;">a</span>
<span style="color: #0000FF;">?<span style="color: #000000;">b
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,971:
 
However, JavaScript has pass-by-sharing semantics, and since 1.0.0 when pwa/p2js (the Phix to JavaScript transpiler) was introduced, a simple "with js" (which works identically to "with javascript_semantics") effectively disables '''both''' underlying semantic mechanisms simultaneously, and causes desktop/Phix to raise fatal runtime errors ("p2js violation: relies on copy on write semantics") indicating where a deep_copy() is needed, which is now a builtin (see builtins\repeat.e for the actual) and is a bit like this:
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">deep_copy<span style="color: #0000FF;">(<span style="color: #004080;">object</span> <span style="color: #000000;">o<span style="color: #0000FF;">)</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">res</span>
Line 1,987:
<span style="color: #004080;">object</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">deep_copy<span style="color: #0000FF;">(<span style="color: #000000;">b<span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?<span style="color: #000000;">c
<!--</langsyntaxhighlight>-->
It is worth pointing out that "with js" and deep_copy() have proved ''staggeringly'' effective and nowhere near as painful as first feared. In just a few months (1.0.0 was released in July 2021) I have tested, fixed where necessary, and marked as javascript compatible ''[https://www.rosettacode.org/mw/index.php?title=Special%3ASearch&search=phixonline some 450 rosettacode entries]'' for Phix, and only ''[https://www.rosettacode.org/mw/index.php?title=Special%3ASearch&search=notonline one tenth]'' of that as incompatible.
 
Or you ''could'' just serialize and deserialize, though it would probably be quite a bit slower:
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins<span style="color: #0000FF;">\<span style="color: #000000;">serialize<span style="color: #0000FF;">.<span style="color: #000000;">e</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">deserialize<span style="color: #0000FF;">(<span style="color: #000000;">serialize<span style="color: #0000FF;">(<span style="color: #000000;">a<span style="color: #0000FF;">)<span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?<span style="color: #000000;">d
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,006:
PHP provides the <code>clone</code> operator ([http://www.php.net/manual/en/language.oop5.cloning.php docs]) for shallow copying, and allows you to hook into a magic class method called <code>__clone()</code> in your classes to do some of the lifting to create deeper copies, but this method won't create a true deep copy if you don't write the code to manage it in each of the child classes.
 
<langsyntaxhighlight PHPlang="php"><?php
class Foo
{
Line 2,026:
echo "Object contains {$object->some_value}, child contains {$object->child->some_value}\n",
"Clone of object contains {$deepcopy->some_value}, child contains {$deepcopy->child->some_value}\n";
?></langsyntaxhighlight>
 
 
Automatically generated deep copies can be created in any situation where your object graph can be serialized (i.e. does not contain any Closures or resources like DB connections or file handles):
 
<langsyntaxhighlight PHPlang="php"><?php
 
// stdClass is a default PHP object
Line 2,044:
 
echo "Object contains {$object->some_value}, child contains {$object->child->some_value}\n",
"Clone of object contains {$deepcopy->some_value}, child contains {$deepcopy->child->some_value}\n";</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Line 2,050:
 
For a known depth, it might be used in combination with other list functions. For example, to copy a non-cyclic structure of depth 2 with '[http://software-lab.de/doc/refM.html#mapcar mapcar]':
<syntaxhighlight lang PicoLisp="picolisp">(mapcar copy List)</langsyntaxhighlight>
Copying non-cyclic structures of arbitrary depth and list-termination could be handled with a custom function (using '[http://software-lab.de/doc/refC.html#cons cons]'):
<langsyntaxhighlight PicoLisplang="picolisp">(de deepCopy (X)
(if (atom X)
X
(cons (deepCopy (car X)) (deepCopy (cdr X))) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (setq A '((a . b) (c d e) f g . e))
-> ((a . b) (c d e) f g . e)
 
Line 2,081:
 
: (== (cadr A) (cadr B))
-> NIL # The same holds for sub-structures</langsyntaxhighlight>
For cyclic structures, the above 'deepCopy' function could be extended, to remember already visited structures and their copies in a mark list:
<langsyntaxhighlight PicoLisplang="picolisp">(de deepCopy (X)
(let Mark NIL
(recur (X)
Line 2,093:
(push 'Mark (cons X @))
(set @ (recurse (car X)))
(con @ (recurse (cdr X))) ) ) ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (setq A '(a b .) B (deepCopy A))
-> (a b .)
: A
Line 2,106:
 
: (== A B)
-> NIL # but they are not identical (pointer-equal)</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Macro PrintStruc(StrucVal)
PrintN(Str(StrucVal#\value1))
PrintN(Chr(StrucVal#\value2))
Line 2,146:
PrintN("Value of 'b':") : PrintStruc(b)
Input()
EndIf</langsyntaxhighlight>
{{out}}<pre>Value of 'a':
20
Line 2,161:
 
=={{header|Python}}==
<langsyntaxhighlight Pythonlang="python">import copy
deepcopy_of_obj = copy.deepcopy(obj)</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 2,172:
to get a new copy:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,187:
(printf "both: ~s\n" (list x (deepcopy x)))))
(try (shared ([x (cons 1 x)]) (list x x)))
</syntaxhighlight>
</lang>
 
Output:
Line 2,208:
* Descends only into <tt>Iterable</tt> collections (like <tt>Array</tt>/<tt>Hash</tt>), which means that a <tt>Pair</tt> or a typical custom object would be considered a leaf node.
 
<syntaxhighlight lang="raku" perl6line>my %x = foo => 0, bar => [0, 1];
my %y = %x.deepmap(*.clone);
 
%x<bar>[1]++;
say %x;
say %y;</langsyntaxhighlight>
 
{{out}}
Line 2,227:
* Doesn't work correctly if the data structure contains elements that can't be properly serialized, such as closures or file handles.
 
<syntaxhighlight lang="raku" perl6line>my %x = foo => 0, bar => [0, 1];
my %y = %x.raku.EVAL;
 
%x<bar>[1]++;
say %x;
say %y;</langsyntaxhighlight>
 
{{out}}
Line 2,243:
Rubyists can hack a deep copy by using the core class Marshal. The intermediate form of <code>Marshal.load(Marshal.dump object)</code> saves the object and any descendant objects.
 
<langsyntaxhighlight lang="ruby"># _orig_ is a Hash that contains an Array.
orig = { :num => 1, :ary => [2, 3] }
orig[:cycle] = orig # _orig_ also contains itself.
Line 2,264:
p [(orig.equal? orig[:cycle]),
(copy.equal? copy[:cycle]),
(not orig.equal? copy)] # => [true, true, true]</langsyntaxhighlight>
 
Marshal cannot dump an object that relates to the system (like Dir or IO), relates to the program (like MatchData or Thread), uses an anonymous class or module, or has a singleton method. (<code>ri Marshal.dump</code> documents this restriction.) If Marshal encounters any such object, then the deep copy fails.
Line 2,273:
This is what the <code>Clone</code> trait exists for although the depth of the copy is arbitrary and up to the type that implements the trait.
 
<langsyntaxhighlight lang="rust">// The compiler can automatically implement Clone on structs (assuming all members have implemented Clone).
#[derive(Clone)]
struct Tree<T> {
Line 2,299:
 
let newtree = tree.clone();
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
(define (deep-copy-1 exp)
;; basic version that copies an arbitrary tree made up of pairs
Line 2,352:
;> (deep-copy-2 t4)
;(#0=(#0#) #1=(#1#))
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
''Object.dclone()'' returns a deep clone of any mutable object.
<langsyntaxhighlight lang="ruby">var src = Hash(foo => 0, bar => [0,1])
 
# Add a cyclic reference
Line 2,370:
# The address of dst
say dst.object_id
say dst{:baz}.object_id</langsyntaxhighlight>
{{out}}
<pre>
Line 2,381:
=={{header|Tcl}}==
Tcl uses an immutable value model that is implemented as copy-on-write at the low level, so deep copies are generally not required. However, they can be achieved by simply appending a letter to the value and stripping it off again:
<langsyntaxhighlight lang="tcl">set deepCopy [string range ${valueToCopy}x 0 end-1]</langsyntaxhighlight>
For objects (as introduced in Tcl 8.6), there is a command to create a copy:
<langsyntaxhighlight lang="tcl">set copiedObject [oo::copy $originalObject]</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 2,395:
 
In the following example, we attempt to deep-copy a custom type, MyMap, which wraps the built-in generic Map type. This succeeds here because of the types of values used but wouldn't succeed if a Map value were, say, some user-defined type which didn't have a clone() method.
<langsyntaxhighlight lang="ecmascript">import "/trait" for Cloneable, CloneableSeq
import "/seq" for Lst
 
Line 2,435:
System.print("\nAfter changes to my2:")
System.print(" my = %(my)")
System.print(" my2 = %(my2)")</langsyntaxhighlight>
 
{{out}}
Line 2,450:
=={{header|Z80 Assembly}}==
There is no built-in type checking, so there's no way to tell apart pointers from actual data without knowing it in advance. Other than that, a deep copy is very easy to perform. A single byte or word can be copied by loading it from memory and writing it to a new location.
<langsyntaxhighlight lang="z80">LD HL,(&C000)
LD (&D000),HL</langsyntaxhighlight>
 
For copying a string or record, the <code>LDIR</code> command makes this very easy, provided you know the size (in bytes) of the data you wish to copy. Label arithmetic is the easiest way to do this for fixed-size data.
 
<langsyntaxhighlight lang="z80">LD HL,MyString
LD DE,UserRam
LD BC,MyString_End-MyString ;the difference between these two addresses is the byte count.
Line 2,464:
 
UserRam:
ds 32,0 ;32 bytes of memory initialized to zero.</langsyntaxhighlight>
 
 
10,327

edits