Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
2
Task/Deepcopy/00-META.yaml
Normal file
2
Task/Deepcopy/00-META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Deepcopy
|
||||
19
Task/Deepcopy/00-TASK.txt
Normal file
19
Task/Deepcopy/00-TASK.txt
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
;Task:
|
||||
Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.
|
||||
|
||||
This is often referred to as [[wp:Deep_copy#Deep_copy|deep copying]], and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.
|
||||
|
||||
If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.
|
||||
|
||||
|
||||
The task should show:
|
||||
|
||||
* Relevant semantics of structures, such as their [[wp:Homogeneity and heterogeneity|homogeneous or heterogeneous]] properties, or containment of (self- or mutual-reference) cycles.
|
||||
|
||||
* Any limitations of the method.
|
||||
|
||||
* That the structure and its copy are different.
|
||||
|
||||
* Suitable links to external documentation for common libraries.
|
||||
<br><br>
|
||||
|
||||
2
Task/Deepcopy/6502-Assembly/deepcopy-1.6502
Normal file
2
Task/Deepcopy/6502-Assembly/deepcopy-1.6502
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
LDA $00 ;read the byte at memory address $00
|
||||
STA $20 ;store it at memory address $20
|
||||
5
Task/Deepcopy/6502-Assembly/deepcopy-2.6502
Normal file
5
Task/Deepcopy/6502-Assembly/deepcopy-2.6502
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
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.
|
||||
14
Task/Deepcopy/6502-Assembly/deepcopy-3.6502
Normal file
14
Task/Deepcopy/6502-Assembly/deepcopy-3.6502
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
;input:
|
||||
;$00,$01 = pointer to source
|
||||
;$07,$08 = pointer to destination
|
||||
;X = bytes to copy
|
||||
;(the memory addresses are arbitrary, but each pair of input addresses MUST be consecutive or this won't work.)
|
||||
memcpy:
|
||||
LDY #0
|
||||
memcpy_again:
|
||||
lda ($00),y
|
||||
sta ($07),y
|
||||
iny
|
||||
dex
|
||||
bne memcpy_again
|
||||
rts
|
||||
4
Task/Deepcopy/AWK/deepcopy.awk
Normal file
4
Task/Deepcopy/AWK/deepcopy.awk
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
BEGIN {
|
||||
for (elem in original)
|
||||
copied[elem] = original[elem]
|
||||
}
|
||||
32
Task/Deepcopy/Aime/deepcopy.aime
Normal file
32
Task/Deepcopy/Aime/deepcopy.aime
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
list L1, L2;
|
||||
|
||||
# Lists are heterogeneous:
|
||||
l_append(L1, 3);
|
||||
l_append(L1, "deep");
|
||||
|
||||
# and may contain self references.
|
||||
# A self references in the last position:
|
||||
l_link(L1, -1, L1);
|
||||
|
||||
# List may also contain mutual references.
|
||||
# Create a new list in the last position:
|
||||
l_n_list(L1, -1);
|
||||
# Add a reference to the top level list to the nested list:
|
||||
l_link(l_q_list(L1, -1), -1, L1);
|
||||
|
||||
# There are no limitations to the deep copy method:
|
||||
l_copy(L2, L1);
|
||||
|
||||
# Modify the string in the original list,
|
||||
# via the self reference in the 3rd position
|
||||
l_r_text(l_q_list(L1, 2), 1, "copy");
|
||||
|
||||
# Show the string in the two lists:
|
||||
o_text(l_query(L2, 1));
|
||||
o_text(l_query(L1, 1));
|
||||
o_byte('\n');
|
||||
|
||||
# And again, via the included self references:
|
||||
o_text(l_query(l_query(L2, 2), 1));
|
||||
o_text(l_query(l_query(L1, 2), 1));
|
||||
o_byte('\n');
|
||||
24
Task/Deepcopy/Arturo/deepcopy.arturo
Normal file
24
Task/Deepcopy/Arturo/deepcopy.arturo
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
x: #[
|
||||
name: "John"
|
||||
surname: "Doe"
|
||||
age: 34
|
||||
hobbies: [
|
||||
"Cycling",
|
||||
"History",
|
||||
"Programming",
|
||||
"Languages",
|
||||
"Psychology",
|
||||
"Buddhism"
|
||||
]
|
||||
sayHello: function [][
|
||||
print "Hello there!"
|
||||
]
|
||||
]
|
||||
|
||||
print ["Name of first person:" x\name]
|
||||
|
||||
y: new x
|
||||
y\name: "Jane"
|
||||
|
||||
print ["Name of first person:" x\name]
|
||||
print ["Name of second person:" y\name]
|
||||
13
Task/Deepcopy/AutoHotkey/deepcopy.ahk
Normal file
13
Task/Deepcopy/AutoHotkey/deepcopy.ahk
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
DeepCopy(Array, Objs=0)
|
||||
{
|
||||
If !Objs
|
||||
Objs := Object()
|
||||
Obj := Array.Clone() ; produces a shallow copy in that any sub-objects are not cloned
|
||||
Objs[&Array] := Obj ; Save this new array - & returns the address of Array in memory
|
||||
For Key, Val in Obj
|
||||
If (IsObject(Val)) ; If it is a subarray
|
||||
Obj[Key] := Objs[&Val] ; If we already know of a reference to this array
|
||||
? Objs[&Val] ; Then point it to the new array (to prevent infinite recursion on self-references
|
||||
: DeepCopy(Val,Objs) ; Otherwise, clone this sub-array
|
||||
Return Obj
|
||||
}
|
||||
5
Task/Deepcopy/Babel/deepcopy-1.pb
Normal file
5
Task/Deepcopy/Babel/deepcopy-1.pb
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
babel> [1 2 3] dup dup 0 7 0 1 move sd !
|
||||
---TOS---
|
||||
[val 0x7 0x2 0x3 ]
|
||||
[val 0x7 0x2 0x3 ]
|
||||
---BOS---
|
||||
5
Task/Deepcopy/Babel/deepcopy-2.pb
Normal file
5
Task/Deepcopy/Babel/deepcopy-2.pb
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
babel> clear [1 2 3] dup cp dup 0 7 0 1 move sd !
|
||||
---TOS---
|
||||
[val 0x7 0x2 0x3 ]
|
||||
[val 0x1 0x2 0x3 ]
|
||||
---BOS---
|
||||
5
Task/Deepcopy/Babel/deepcopy-3.pb
Normal file
5
Task/Deepcopy/Babel/deepcopy-3.pb
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
babel> ((1 2) (3 4) (5 6)) cp
|
||||
babel> {lsnum !} each
|
||||
( 1 2 )
|
||||
( 3 4 )
|
||||
( 5 6 )
|
||||
3
Task/Deepcopy/Babel/deepcopy-4.pb
Normal file
3
Task/Deepcopy/Babel/deepcopy-4.pb
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
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
|
||||
3
Task/Deepcopy/Babel/deepcopy-5.pb
Normal file
3
Task/Deepcopy/Babel/deepcopy-5.pb
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
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
|
||||
29
Task/Deepcopy/C++/deepcopy.cpp
Normal file
29
Task/Deepcopy/C++/deepcopy.cpp
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
#include <array>
|
||||
#include <iostream>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
int main()
|
||||
{
|
||||
// make a nested structure to copy - a map of arrays containing vectors of strings
|
||||
auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"};
|
||||
auto myColors = std::vector<std::string>{"red", "green", "blue"};
|
||||
auto myArray = std::array<std::vector<std::string>, 2>{myNumbers, myColors};
|
||||
auto myMap = std::map<int, decltype(myArray)> {{3, myArray}, {7, myArray}};
|
||||
|
||||
// make a deep copy of the map
|
||||
auto mapCopy = myMap;
|
||||
|
||||
// modify the copy
|
||||
mapCopy[3][0][1] = "2";
|
||||
mapCopy[7][1][2] = "purple";
|
||||
|
||||
std::cout << "the original values:\n";
|
||||
std::cout << myMap[3][0][1] << "\n";
|
||||
std::cout << myMap[7][1][2] << "\n\n";
|
||||
|
||||
std::cout << "the modified copy:\n";
|
||||
std::cout << mapCopy[3][0][1] << "\n";
|
||||
std::cout << mapCopy[7][1][2] << "\n";
|
||||
}
|
||||
28
Task/Deepcopy/C-sharp/deepcopy.cs
Normal file
28
Task/Deepcopy/C-sharp/deepcopy.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
using System;
|
||||
|
||||
namespace prog
|
||||
{
|
||||
class MainClass
|
||||
{
|
||||
class MyClass : ICloneable
|
||||
{
|
||||
public MyClass() { f = new int[3]{2,3,5}; c = '1'; }
|
||||
|
||||
public object Clone()
|
||||
{
|
||||
MyClass cpy = (MyClass) this.MemberwiseClone();
|
||||
cpy.f = (int[]) this.f.Clone();
|
||||
return cpy;
|
||||
}
|
||||
|
||||
public char c;
|
||||
public int[] f;
|
||||
}
|
||||
|
||||
public static void Main( string[] args )
|
||||
{
|
||||
MyClass c1 = new MyClass();
|
||||
MyClass c2 = (MyClass) c1.Clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
47
Task/Deepcopy/C/deepcopy-1.c
Normal file
47
Task/Deepcopy/C/deepcopy-1.c
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
#include<stdio.h>
|
||||
|
||||
typedef struct{
|
||||
int a;
|
||||
}layer1;
|
||||
|
||||
typedef struct{
|
||||
layer1 l1;
|
||||
float b,c;
|
||||
}layer2;
|
||||
|
||||
typedef struct{
|
||||
layer2 l2;
|
||||
layer1 l1;
|
||||
int d,e;
|
||||
}layer3;
|
||||
|
||||
void showCake(layer3 cake){
|
||||
printf("\ncake.d = %d",cake.d);
|
||||
printf("\ncake.e = %d",cake.e);
|
||||
printf("\ncake.l1.a = %d",cake.l1.a);
|
||||
printf("\ncake.l2.b = %f",cake.l2.b);
|
||||
printf("\ncake.l2.l1.a = %d",cake.l2.l1.a);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
layer3 cake1,cake2;
|
||||
|
||||
cake1.d = 1;
|
||||
cake1.e = 2;
|
||||
cake1.l1.a = 3;
|
||||
cake1.l2.b = 4;
|
||||
cake1.l2.l1.a = 5;
|
||||
|
||||
printf("Cake 1 is : ");
|
||||
showCake(cake1);
|
||||
|
||||
cake2 = cake1;
|
||||
|
||||
cake2.l2.b += cake2.l2.l1.a;
|
||||
|
||||
printf("\nCake 2 is : ");
|
||||
showCake(cake2);
|
||||
|
||||
return 0;
|
||||
}
|
||||
90
Task/Deepcopy/C/deepcopy-2.c
Normal file
90
Task/Deepcopy/C/deepcopy-2.c
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
#include<stdlib.h>
|
||||
#include<stdio.h>
|
||||
|
||||
typedef struct elem{
|
||||
int data;
|
||||
struct elem* next;
|
||||
}cell;
|
||||
|
||||
typedef cell* list;
|
||||
|
||||
void addToList(list *a,int num){
|
||||
list temp, holder;
|
||||
|
||||
if(*a==NULL){
|
||||
*a = (list)malloc(sizeof(cell));
|
||||
(*a)->data = num;
|
||||
(*a)->next = NULL;
|
||||
}
|
||||
else{
|
||||
temp = *a;
|
||||
|
||||
while(temp->next!=NULL)
|
||||
temp = temp->next;
|
||||
|
||||
holder = (list)malloc(sizeof(cell));
|
||||
holder->data = num;
|
||||
holder->next = NULL;
|
||||
|
||||
temp->next = holder;
|
||||
}
|
||||
}
|
||||
|
||||
list copyList(list a){
|
||||
list b, tempA, tempB, temp;
|
||||
|
||||
if(a!=NULL){
|
||||
b = (list)malloc(sizeof(cell));
|
||||
b->data = a->data;
|
||||
b->next = NULL;
|
||||
|
||||
tempA = a->next;
|
||||
tempB = b;
|
||||
|
||||
while(tempA!=NULL){
|
||||
temp = (list)malloc(sizeof(cell));
|
||||
temp->data = tempA->data;
|
||||
temp->next = NULL;
|
||||
|
||||
tempB->next = temp;
|
||||
tempB = temp;
|
||||
|
||||
tempA = tempA->next;
|
||||
}
|
||||
}
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
void printList(list a){
|
||||
list temp = a;
|
||||
|
||||
while(temp!=NULL){
|
||||
printf("%d,",temp->data);
|
||||
temp = temp->next;
|
||||
}
|
||||
printf("\b");
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
list a,b;
|
||||
int i;
|
||||
|
||||
for(i=1;i<=5;i++)
|
||||
addToList(&a,i);
|
||||
|
||||
printf("List a is : ");
|
||||
|
||||
printList(a);
|
||||
|
||||
b = copyList(a);
|
||||
|
||||
free(a);
|
||||
|
||||
printf("\nList a destroyed, List b is : ");
|
||||
|
||||
printList(b);
|
||||
|
||||
return 0;
|
||||
}
|
||||
7
Task/Deepcopy/Common-Lisp/deepcopy.lisp
Normal file
7
Task/Deepcopy/Common-Lisp/deepcopy.lisp
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
$ clisp -q
|
||||
[1]> (setf *print-circle* t)
|
||||
T
|
||||
[2]> (let ((a (cons 1 nil))) (setf (cdr a) a)) ;; create circular list
|
||||
#1=(1 . #1#)
|
||||
[3]> (read-from-string "#1=(1 . #1#)") ;; read it from a string
|
||||
#1=(1 . #1#) ;; a similar circular list is returned
|
||||
51
Task/Deepcopy/Delphi/deepcopy.delphi
Normal file
51
Task/Deepcopy/Delphi/deepcopy.delphi
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
program DeepCopyApp;
|
||||
|
||||
{$APPTYPE CONSOLE}
|
||||
|
||||
uses
|
||||
System.TypInfo;
|
||||
|
||||
type
|
||||
TTypeA = record
|
||||
value1: integer;
|
||||
value2: char;
|
||||
value3: string[10];
|
||||
value4: Boolean;
|
||||
function DeepCopy: TTypeA;
|
||||
end;
|
||||
|
||||
{ TTypeA }
|
||||
|
||||
function TTypeA.DeepCopy: TTypeA;
|
||||
begin
|
||||
CopyRecord(@result, @self, TypeInfo(TTypeA));
|
||||
end;
|
||||
|
||||
var
|
||||
a, b: TTypeA;
|
||||
|
||||
begin
|
||||
a.value1 := 10;
|
||||
a.value2 := 'A';
|
||||
a.value3 := 'OK';
|
||||
a.value4 := True;
|
||||
|
||||
b := a.DeepCopy;
|
||||
a.value1 := 20;
|
||||
a.value2 := 'B';
|
||||
a.value3 := 'NOK';
|
||||
a.value4 := False;
|
||||
|
||||
Writeln('Value of "a":');
|
||||
Writeln(a.value1);
|
||||
Writeln(a.value2);
|
||||
Writeln(a.value3);
|
||||
Writeln(a.value4);
|
||||
|
||||
Writeln(#10'Value of "b":');
|
||||
Writeln(b.value1);
|
||||
Writeln(b.value2);
|
||||
Writeln(b.value3);
|
||||
Writeln(b.value4);
|
||||
readln;
|
||||
end.
|
||||
4
Task/Deepcopy/E/deepcopy-1.e
Normal file
4
Task/Deepcopy/E/deepcopy-1.e
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
def deSubgraphKit := <elib:serial.deSubgraphKit>
|
||||
def deepcopy(x) {
|
||||
return deSubgraphKit.recognize(x, deSubgraphKit.makeBuilder())
|
||||
}
|
||||
22
Task/Deepcopy/E/deepcopy-2.e
Normal file
22
Task/Deepcopy/E/deepcopy-2.e
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
? def x := ["a" => 1, "b" => [x].diverge()]
|
||||
# value: ["a" => 1, "b" => [<***CYCLE***>].diverge()]
|
||||
|
||||
? def y := deepcopy(x)
|
||||
# value: ["a" => 1, "b" => [<***CYCLE***>].diverge()]
|
||||
|
||||
? y["b"].push(2)
|
||||
|
||||
? y
|
||||
# value: ["a" => 1, "b" => [<***CYCLE***>, 2].diverge()]
|
||||
|
||||
? x
|
||||
# value: ["a" => 1, "b" => [<***CYCLE***>].diverge()]
|
||||
|
||||
? y["b"][0] == y
|
||||
# value: true
|
||||
|
||||
? y["b"][0] == x
|
||||
# value: false
|
||||
|
||||
? x["b"][0] == x
|
||||
# value: true
|
||||
26
Task/Deepcopy/Factor/deepcopy-1.factor
Normal file
26
Task/Deepcopy/Factor/deepcopy-1.factor
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
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@
|
||||
16
Task/Deepcopy/Factor/deepcopy-2.factor
Normal file
16
Task/Deepcopy/Factor/deepcopy-2.factor
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
! 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@
|
||||
38
Task/Deepcopy/FreeBASIC/deepcopy.basic
Normal file
38
Task/Deepcopy/FreeBASIC/deepcopy.basic
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
Type DeepCopy
|
||||
value1 As Integer
|
||||
value2 As String * 1
|
||||
value3 As String
|
||||
value4 As Boolean
|
||||
value5 As Double
|
||||
End Type
|
||||
Dim As DeepCopy a, b
|
||||
|
||||
a.value1 = 10
|
||||
a.value2 = "A"
|
||||
a.value3 = "OK"
|
||||
a.value4 = True
|
||||
a.value5 = 1.985766472453666
|
||||
|
||||
b = a
|
||||
a.value1 = 20
|
||||
a.value2 = "B"
|
||||
a.value3 = "NOK"
|
||||
a.value4 = False
|
||||
a.value5 = 3.148556644245367
|
||||
|
||||
Print !"Valor de \"a\":"
|
||||
Print a.value1
|
||||
Print a.value2
|
||||
Print a.value3
|
||||
Print a.value4
|
||||
Print a.value5
|
||||
|
||||
Print !"\nValor \"b\":"
|
||||
With b
|
||||
Print .value1
|
||||
Print .value2
|
||||
Print .value3
|
||||
Print .value4
|
||||
Print .value5
|
||||
End With
|
||||
Sleep
|
||||
37
Task/Deepcopy/Go/deepcopy-1.go
Normal file
37
Task/Deepcopy/Go/deepcopy-1.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// a complex data structure
|
||||
type cds struct {
|
||||
i int // no special handling needed for deep copy
|
||||
s string // no special handling
|
||||
b []byte // copied easily with append function
|
||||
m map[int]bool // deep copy requires looping
|
||||
}
|
||||
|
||||
// a method
|
||||
func (c cds) deepcopy() *cds {
|
||||
// copy what you can in one line
|
||||
r := &cds{c.i, c.s, append([]byte{}, c.b...), make(map[int]bool)}
|
||||
// populate map with a loop
|
||||
for k, v := range c.m {
|
||||
r.m[k] = v
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// demo
|
||||
func main() {
|
||||
// create and populate a structure
|
||||
c1 := &cds{1, "one", []byte("unit"), map[int]bool{1: true}}
|
||||
fmt.Println(c1) // show it
|
||||
c2 := c1.deepcopy() // copy it
|
||||
fmt.Println(c2) // show copy
|
||||
c1.i = 0 // change original
|
||||
c1.s = "nil"
|
||||
copy(c1.b, "zero")
|
||||
c1.m[1] = false
|
||||
fmt.Println(c1) // show changes
|
||||
fmt.Println(c2) // show copy unaffected
|
||||
}
|
||||
60
Task/Deepcopy/Go/deepcopy-2.go
Normal file
60
Task/Deepcopy/Go/deepcopy-2.go
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// a type that allows cyclic structures
|
||||
type node []*node
|
||||
|
||||
// recursively print the contents of a node
|
||||
func (n *node) list() {
|
||||
if n == nil {
|
||||
fmt.Println(n)
|
||||
return
|
||||
}
|
||||
listed := map[*node]bool{nil: true}
|
||||
var r func(*node)
|
||||
r = func(n *node) {
|
||||
listed[n] = true
|
||||
fmt.Printf("%p -> %v\n", n, *n)
|
||||
for _, m := range *n {
|
||||
if !listed[m] {
|
||||
r(m)
|
||||
}
|
||||
}
|
||||
}
|
||||
r(n)
|
||||
}
|
||||
|
||||
// construct a deep copy of a node
|
||||
func (n *node) ccopy() *node {
|
||||
if n == nil {
|
||||
return n
|
||||
}
|
||||
cc := map[*node]*node{nil: nil}
|
||||
var r func(*node) *node
|
||||
r = func(n *node) *node {
|
||||
c := make(node, len(*n))
|
||||
cc[n] = &c
|
||||
for i, m := range *n {
|
||||
d, ok := cc[m]
|
||||
if !ok {
|
||||
d = r(m)
|
||||
}
|
||||
c[i] = d
|
||||
}
|
||||
return &c
|
||||
}
|
||||
return r(n)
|
||||
}
|
||||
|
||||
func main() {
|
||||
a := node{nil}
|
||||
c := &node{&node{&a}}
|
||||
a[0] = c
|
||||
c.list()
|
||||
cc := c.ccopy()
|
||||
fmt.Println("copy:")
|
||||
cc.list()
|
||||
fmt.Println("original:")
|
||||
c.list()
|
||||
}
|
||||
62
Task/Deepcopy/Go/deepcopy-3.go
Normal file
62
Task/Deepcopy/Go/deepcopy-3.go
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// capability requested by task
|
||||
func deepcopy(dst, src interface{}) error {
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
enc := gob.NewEncoder(w)
|
||||
err = enc.Encode(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dec := gob.NewDecoder(r)
|
||||
return dec.Decode(dst)
|
||||
}
|
||||
|
||||
// define linked list type, an example of a recursive type
|
||||
type link struct {
|
||||
Value string
|
||||
Next *link
|
||||
}
|
||||
|
||||
// method satisfies stringer interface for fmt.Println
|
||||
func (l *link) String() string {
|
||||
if l == nil {
|
||||
return "nil"
|
||||
}
|
||||
s := "(" + l.Value
|
||||
for l = l.Next; l != nil; l = l.Next {
|
||||
s += " " + l.Value
|
||||
}
|
||||
return s + ")"
|
||||
}
|
||||
|
||||
func main() {
|
||||
// create a linked list with two elements
|
||||
l1 := &link{"a", &link{Value: "b"}}
|
||||
// print original
|
||||
fmt.Println(l1)
|
||||
// declare a variable to hold deep copy
|
||||
var l2 *link
|
||||
// copy
|
||||
if err := deepcopy(&l2, l1); err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
// print copy
|
||||
fmt.Println(l2)
|
||||
// now change contents of original list
|
||||
l1.Value, l1.Next.Value = "c", "d"
|
||||
// show that it is changed
|
||||
fmt.Println(l1)
|
||||
// show that copy is unaffected
|
||||
fmt.Println(l2)
|
||||
}
|
||||
24
Task/Deepcopy/Icon/deepcopy-1.icon
Normal file
24
Task/Deepcopy/Icon/deepcopy-1.icon
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
procedure deepcopy(A, cache) #: return a deepcopy of A
|
||||
local k
|
||||
|
||||
/cache := table() # used to handle multireferenced objects
|
||||
if \cache[A] then return cache[A]
|
||||
|
||||
case type(A) of {
|
||||
"table"|"list": {
|
||||
cache[A] := copy(A)
|
||||
every cache[A][k := key(A)] := deepcopy(A[k], cache)
|
||||
}
|
||||
"set": {
|
||||
cache[A] := set()
|
||||
every insert(cache[A], deepcopy(!A, cache))
|
||||
}
|
||||
default: { # records and objects (encoded as records)
|
||||
cache[A] := copy(A)
|
||||
if match("record ",image(A)) then {
|
||||
every cache[A][k := key(A)] := deepcopy(A[k], cache)
|
||||
}
|
||||
}
|
||||
}
|
||||
return .cache[A]
|
||||
end
|
||||
54
Task/Deepcopy/Icon/deepcopy-2.icon
Normal file
54
Task/Deepcopy/Icon/deepcopy-2.icon
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
link printf,ximage
|
||||
|
||||
procedure main()
|
||||
|
||||
knot := makeknot() # create a structure with loops
|
||||
knota := knot # copy by assignment (reference)
|
||||
knotc := copy(knot) # built-in copy (shallow)
|
||||
knotdc := deepcopy(knot) # deep copy
|
||||
|
||||
|
||||
showdeep("knota (assignment) vs. knot",knota,knot)
|
||||
showdeep("knotc (copy) vs. knot",knotc,knot)
|
||||
showdeep("knotdc (deepcopy) vs. knot",knotdc,knot)
|
||||
|
||||
xdump("knot (original)",knot)
|
||||
xdump("knota (assignment)",knota)
|
||||
xdump("knotc (copy)",knotc)
|
||||
xdump("knotdc (deepcopy)",knotdc)
|
||||
end
|
||||
|
||||
record rec1(a,b,c) # record for example
|
||||
|
||||
class Class1(a1,a2) # class - looks like a record under the covers
|
||||
method one()
|
||||
self.a1 := 1
|
||||
return
|
||||
end
|
||||
initially
|
||||
self.a1 := 0
|
||||
end
|
||||
|
||||
|
||||
procedure makeknot() #: return a homogeneous structure with loops
|
||||
L := [9,8,7]
|
||||
T := table()
|
||||
T["a"] := 1
|
||||
R := rec1(T)
|
||||
S := set(R)
|
||||
C := Class1()
|
||||
C.one()
|
||||
T["knot"] := [L,R,S,C]
|
||||
put(L,R,S,T,C)
|
||||
return L
|
||||
end
|
||||
|
||||
procedure showdeep(tag,XC,X) #: demo to show (non-)equivalence of list elements
|
||||
printf("Analysis of copy depth for %s:\n",tag)
|
||||
showequiv(XC,X)
|
||||
every showequiv(XC[i := 1 to *X],X[i])
|
||||
end
|
||||
|
||||
procedure showequiv(x,y) #: show (non-)equivalence of two values
|
||||
return printf(" %i %s %i\n",x,if x === y then "===" else "~===",y)
|
||||
end
|
||||
6
Task/Deepcopy/J/deepcopy.j
Normal file
6
Task/Deepcopy/J/deepcopy.j
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
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
|
||||
159
Task/Deepcopy/Java/deepcopy.java
Normal file
159
Task/Deepcopy/Java/deepcopy.java
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
|
||||
public class DeepCopy {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Person p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101"));
|
||||
Person p2 = p1;
|
||||
|
||||
System.out.printf("Demonstrate shallow copy. Both are the same object.%n");
|
||||
System.out.printf("Person p1 = %s%n", p1);
|
||||
System.out.printf("Person p2 = %s%n", p2);
|
||||
System.out.printf("Set city on person 2. City on both objects is changed.%n");
|
||||
p2.getAddress().setCity("New York");
|
||||
System.out.printf("Person p1 = %s%n", p1);
|
||||
System.out.printf("Person p2 = %s%n", p2);
|
||||
|
||||
p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101"));
|
||||
p2 = new Person(p1);
|
||||
System.out.printf("%nDemonstrate copy constructor. Object p2 is a deep copy of p1.%n");
|
||||
System.out.printf("Person p1 = %s%n", p1);
|
||||
System.out.printf("Person p2 = %s%n", p2);
|
||||
System.out.printf("Set city on person 2. City on objects is different.%n");
|
||||
p2.getAddress().setCity("New York");
|
||||
System.out.printf("Person p1 = %s%n", p1);
|
||||
System.out.printf("Person p2 = %s%n", p2);
|
||||
|
||||
p2 = (Person) deepCopy(p1);
|
||||
System.out.printf("%nDemonstrate serialization. Object p2 is a deep copy of p1.%n");
|
||||
System.out.printf("Person p1 = %s%n", p1);
|
||||
System.out.printf("Person p2 = %s%n", p2);
|
||||
System.out.printf("Set city on person 2. City on objects is different.%n");
|
||||
p2.getAddress().setCity("New York");
|
||||
System.out.printf("Person p1 = %s%n", p1);
|
||||
System.out.printf("Person p2 = %s%n", p2);
|
||||
|
||||
p2 = (Person) p1.clone();
|
||||
System.out.printf("%nDemonstrate cloning. Object p2 is a deep copy of p1.%n");
|
||||
System.out.printf("Person p1 = %s%n", p1);
|
||||
System.out.printf("Person p2 = %s%n", p2);
|
||||
System.out.printf("Set city on person 2. City on objects is different.%n");
|
||||
p2.getAddress().setCity("New York");
|
||||
System.out.printf("Person p1 = %s%n", p1);
|
||||
System.out.printf("Person p2 = %s%n", p2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a deep copy of any Java object that is passed.
|
||||
*/
|
||||
private static Object deepCopy(Object object) {
|
||||
try {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ObjectOutputStream outputStrm = new ObjectOutputStream(outputStream);
|
||||
outputStrm.writeObject(object);
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
|
||||
ObjectInputStream objInputStream = new ObjectInputStream(inputStream);
|
||||
return objInputStream.readObject();
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Address implements Serializable, Cloneable {
|
||||
|
||||
private static final long serialVersionUID = -7073778041809445593L;
|
||||
|
||||
private String street;
|
||||
private String city;
|
||||
private String state;
|
||||
private String postalCode;
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
public String getPostalCode() {
|
||||
return postalCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "[street=" + street + ", city=" + city + ", state=" + state + ", code=" + postalCode + "]";
|
||||
}
|
||||
|
||||
public Address(String s, String c, String st, String p) {
|
||||
street = s;
|
||||
city = c;
|
||||
state = st;
|
||||
postalCode = p;
|
||||
}
|
||||
|
||||
// Copy constructor
|
||||
public Address(Address add) {
|
||||
street = add.street;
|
||||
city = add.city;
|
||||
state = add.state;
|
||||
postalCode = add.postalCode;
|
||||
}
|
||||
|
||||
// Support Cloneable
|
||||
@Override
|
||||
public Object clone() {
|
||||
return new Address(this);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class Person implements Serializable, Cloneable {
|
||||
private static final long serialVersionUID = -521810583786595050L;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Address address;
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "[first name=" + firstName + ", last name=" + lastName + ", address=" + address + "]";
|
||||
}
|
||||
|
||||
public Person(String fn, String ln, Address add) {
|
||||
firstName = fn;
|
||||
lastName = ln;
|
||||
address = add;
|
||||
}
|
||||
|
||||
// Copy Constructor
|
||||
public Person(Person person) {
|
||||
firstName = person.firstName;
|
||||
lastName = person.lastName;
|
||||
address = new Address(person.address); // Invoke copy constructor of mutable sub-objects.
|
||||
}
|
||||
|
||||
// Support Cloneable
|
||||
@Override
|
||||
public Object clone() {
|
||||
return new Person(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
8
Task/Deepcopy/JavaScript/deepcopy-1.js
Normal file
8
Task/Deepcopy/JavaScript/deepcopy-1.js
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
var deepcopy = function(o){
|
||||
return JSON.parse(JSON.stringify(src));
|
||||
};
|
||||
|
||||
var src = {foo:0,bar:[0,1]};
|
||||
print(JSON.stringify(src));
|
||||
var dst = deepcopy(src);
|
||||
print(JSON.stringify(src));
|
||||
8
Task/Deepcopy/JavaScript/deepcopy-2.js
Normal file
8
Task/Deepcopy/JavaScript/deepcopy-2.js
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
var deepcopy = function(o){
|
||||
return eval(uneval(o));
|
||||
};
|
||||
var src = {foo:0,bar:[0,1]};
|
||||
src['baz'] = src;
|
||||
print(uneval(src));
|
||||
var dst = deepcopy(src);
|
||||
print(uneval(src));
|
||||
3
Task/Deepcopy/Julia/deepcopy.julia
Normal file
3
Task/Deepcopy/Julia/deepcopy.julia
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
# v0.6.0
|
||||
|
||||
cp = deepcopy(obj)
|
||||
71
Task/Deepcopy/Kotlin/deepcopy.kotlin
Normal file
71
Task/Deepcopy/Kotlin/deepcopy.kotlin
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
// Version 1.2.31
|
||||
|
||||
import java.io.Serializable
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ObjectOutputStream
|
||||
import java.io.ObjectInputStream
|
||||
|
||||
fun <T : Serializable> deepCopy(obj: T?): T? {
|
||||
if (obj == null) return null
|
||||
val baos = ByteArrayOutputStream()
|
||||
val oos = ObjectOutputStream(baos)
|
||||
oos.writeObject(obj)
|
||||
oos.close()
|
||||
val bais = ByteArrayInputStream(baos.toByteArray())
|
||||
val ois = ObjectInputStream(bais)
|
||||
@Suppress("unchecked_cast")
|
||||
return ois.readObject() as T
|
||||
}
|
||||
|
||||
class Person(
|
||||
val name: String,
|
||||
var age: Int,
|
||||
val sex: Char,
|
||||
var income: Double,
|
||||
var partner: Person?
|
||||
) : Serializable
|
||||
|
||||
fun printDetails(p1: Person, p2: Person?, p3: Person, p4: Person?) {
|
||||
with (p3) {
|
||||
println("Name : $name")
|
||||
println("Age : $age")
|
||||
println("Sex : $sex")
|
||||
println("Income : $income")
|
||||
if (p4 == null) {
|
||||
println("Partner : None")
|
||||
}
|
||||
else {
|
||||
println("Partner :-")
|
||||
with (p4) {
|
||||
println(" Name : $name")
|
||||
println(" Age : $age")
|
||||
println(" Sex : $sex")
|
||||
println(" Income : $income")
|
||||
}
|
||||
}
|
||||
println("\nSame person as original '$name' == ${p1 === p3}")
|
||||
if (p4 != null) {
|
||||
println("Same person as original '${p2!!.name}' == ${p2 === p4}")
|
||||
}
|
||||
}
|
||||
println()
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
var p1 = Person("John", 35, 'M', 50000.0, null)
|
||||
val p2 = Person("Jane", 32, 'F', 25000.0, p1)
|
||||
p1.partner = p2
|
||||
var p3 = deepCopy(p1)
|
||||
val p4 = p3!!.partner
|
||||
printDetails(p1, p2, p3, p4)
|
||||
|
||||
println("..or, say, after 2 years have elapsed:-\n")
|
||||
with (p1) {
|
||||
age = 37
|
||||
income = 55000.0
|
||||
partner = null
|
||||
}
|
||||
p3 = deepCopy(p1)
|
||||
printDetails(p1, null, p3!!, null)
|
||||
}
|
||||
1
Task/Deepcopy/Lasso/deepcopy.lasso
Normal file
1
Task/Deepcopy/Lasso/deepcopy.lasso
Normal file
|
|
@ -0,0 +1 @@
|
|||
local(copy) = #myobject->ascopydeep
|
||||
19
Task/Deepcopy/Lingo/deepcopy-1.lingo
Normal file
19
Task/Deepcopy/Lingo/deepcopy-1.lingo
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
-- Supports lists, property lists, images, script instances and scalar values (integer, float, string, symbol).
|
||||
on deepcopy (var, cycleCheck)
|
||||
case ilk(var) of
|
||||
#list, #propList, #image:
|
||||
return var.duplicate()
|
||||
#instance:
|
||||
if string(var) starts "<Xtra " then return var -- deep copy makes no sense for Xtra instances
|
||||
if voidP(cycleCheck) then cycleCheck = [:]
|
||||
if not voidP(cycleCheck[var]) then return cycleCheck[var]
|
||||
copy = var.script.rawNew()
|
||||
cycleCheck[var] = copy
|
||||
repeat with i = 1 to var.count
|
||||
copy.setProp(var.getPropAt(i), deepcopy(var[i], cycleCheck))
|
||||
end repeat
|
||||
return copy
|
||||
otherwise:
|
||||
return var
|
||||
end case
|
||||
end
|
||||
8
Task/Deepcopy/Lingo/deepcopy-2.lingo
Normal file
8
Task/Deepcopy/Lingo/deepcopy-2.lingo
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
val = [#foo:42, "bar":[1,2,3, "Hello world!"]]
|
||||
put deepcopy(val)
|
||||
-- [#foo: 42, "bar": [1, 2, 3, "Hello world!"]]
|
||||
|
||||
val = script("MyClass").new()
|
||||
val.foo = 42
|
||||
val.bar = [1, 2, 3, "Hello world!"]]
|
||||
copy = deepcopy(val)
|
||||
25
Task/Deepcopy/Lua/deepcopy-1.lua
Normal file
25
Task/Deepcopy/Lua/deepcopy-1.lua
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
function _deepcopy(o, tables)
|
||||
|
||||
if type(o) ~= 'table' then
|
||||
return o
|
||||
end
|
||||
|
||||
if tables[o] ~= nil then
|
||||
return tables[o]
|
||||
end
|
||||
|
||||
local new_o = {}
|
||||
tables[o] = new_o
|
||||
|
||||
for k, v in next, o, nil do
|
||||
local new_k = _deepcopy(k, tables)
|
||||
local new_v = _deepcopy(v, tables)
|
||||
new_o[new_k] = new_v
|
||||
end
|
||||
|
||||
return new_o
|
||||
end
|
||||
|
||||
function deepcopy(o)
|
||||
return _deepcopy(o, {})
|
||||
end
|
||||
38
Task/Deepcopy/Lua/deepcopy-2.lua
Normal file
38
Task/Deepcopy/Lua/deepcopy-2.lua
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
function deepcopy(o, mode)
|
||||
|
||||
if type(o) ~= 'table' then
|
||||
return o
|
||||
end
|
||||
|
||||
mode = mode and mode:lower() or 'v'
|
||||
local deep_keys = mode:find('k')
|
||||
local deep_values = mode:find('v')
|
||||
|
||||
local new_t = {}
|
||||
local stack = {o}
|
||||
local tables = {[o] = new_t}
|
||||
|
||||
local function copy(v)
|
||||
if type(v) ~= 'table' then
|
||||
return v
|
||||
end
|
||||
if tables[v] == nil then
|
||||
tables[v] = {}
|
||||
stack[#stack+1] = v
|
||||
end
|
||||
return tables[v]
|
||||
end
|
||||
|
||||
while #stack ~= 0 do
|
||||
local t = table.remove(stack)
|
||||
local new_t = tables[t]
|
||||
|
||||
for k,v in next, t, nil do
|
||||
if deep_keys then k = copy(k) end
|
||||
if deep_values then v = copy(v) end
|
||||
new_t[k] = v
|
||||
end
|
||||
end
|
||||
|
||||
return new_t
|
||||
end
|
||||
90
Task/Deepcopy/Lua/deepcopy-3.lua
Normal file
90
Task/Deepcopy/Lua/deepcopy-3.lua
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
function deepcopy(o, mode)
|
||||
|
||||
if type(o) ~= 'table' then
|
||||
return o
|
||||
end
|
||||
|
||||
mode = mode and mode:lower() or 'v'
|
||||
local deep_keys = mode:find('k')
|
||||
local deep_values = mode:find('v')
|
||||
|
||||
local tables = {[o] = {}} -- list of known tables (to handle circular tables)
|
||||
local stack = {o} -- first table which will be popped from stack is the root table
|
||||
-- and the key must be `nil` because we are at the beginning
|
||||
-- of the root table. since it's `nil`, we don't need to put it
|
||||
-- on the stack - `table.remove()` will by default return `nil`
|
||||
-- when called on an empty table.
|
||||
|
||||
while #stack ~= 0 do
|
||||
local t, new_t, k, v = table.remove(stack) -- assigns only to `t`,
|
||||
-- other variables are set to `nil`
|
||||
if t ~= 0 then
|
||||
k = table.remove(stack) -- restore the context
|
||||
|
||||
else -- we finished copying the key, now copy the value
|
||||
t = stack[#stack] -- get the parent table to retrieve the value from
|
||||
k = stack[#stack-1] -- get saved key
|
||||
t = t[k] -- retrieve the value from the parent table and set it as the current table
|
||||
k = nil -- reset key (start traversing the value table from the beginning)
|
||||
end
|
||||
new_t = tables[t] -- get the new table from the list of known tables
|
||||
|
||||
if k ~= nil then -- this is always true except for
|
||||
-- 1. when we just popped the root table `o`
|
||||
-- 2. when we just finished copying the key table
|
||||
-- and now we have to copy the value table
|
||||
local v = t[k] -- get the original value
|
||||
-- if we want to deep-copy keys, then get its copy from the list
|
||||
-- of known tables. if it's not there, then it isn't a table,
|
||||
-- so keep its original value. same goes for the value.
|
||||
if deep_keys then k = tables[k] or k end
|
||||
if deep_values then v = tables[v] or v end
|
||||
new_t[k] = v -- put value into the new table
|
||||
end
|
||||
|
||||
k,v = next(t,k) -- in case we have just started traversing the root table `o`, this retrieves
|
||||
-- the first key and value, as well as in case we have just finished copying
|
||||
-- the key table and are now copying the value table. otherwise, it continues
|
||||
-- where we left off when we descended into subtable.
|
||||
|
||||
while k ~= nil do
|
||||
-- we need to deep-copy the key/value only if
|
||||
-- 1. we want to do it (eg. `mode` specifies to deep-copy keys/values), AND
|
||||
-- 2. it is a table, AND
|
||||
-- 3. we haven't copied it already (and are not copying it right now)
|
||||
local copy_key = deep_keys and type(k) == 'table' and not tables[k]
|
||||
local copy_value = deep_values and type(v) == 'table' and not tables[v]
|
||||
|
||||
if not copy_key and not copy_value then -- boring stuff
|
||||
-- if either `deep_keys` is `nil` (we don't want to deep-copy keys)
|
||||
-- or `tables[k]` is `nil` (the key is not a table), then keep the key's original value,
|
||||
-- otherwise use the value saved in `tables`. same goes for the value.
|
||||
local new_k = deep_keys and tables[k] or k
|
||||
local new_v = deep_values and tables[v] or v
|
||||
new_t[new_k] = new_v -- put the value into the new table
|
||||
|
||||
else -- copy_key or copy_value
|
||||
stack[#stack+1] = k -- save current context
|
||||
stack[#stack+1] = t
|
||||
|
||||
if copy_key then
|
||||
t = k -- descend into the key table
|
||||
if copy_value then
|
||||
stack[#stack+1] = 0 -- remember we have to copy the value table as well
|
||||
tables[v] = {} -- create new table for the value beforehand
|
||||
end
|
||||
else -- copy only the value
|
||||
t = v -- descent into the value table
|
||||
end
|
||||
|
||||
new_t = {} -- create new table
|
||||
tables[t] = new_t -- add it to the list of known tables
|
||||
k = nil -- reset the key
|
||||
end
|
||||
|
||||
k,v = next(t,k) -- get next key/value (or first, in case we just descended into a subtable)
|
||||
end
|
||||
end
|
||||
|
||||
return tables[o] -- return the copy corresponding to the root table `o`
|
||||
end
|
||||
9
Task/Deepcopy/Mathematica/deepcopy.math
Normal file
9
Task/Deepcopy/Mathematica/deepcopy.math
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
a = {"foo", \[Pi], {<|
|
||||
"deep" -> {# +
|
||||
1 &, {{"Mathematica"}, {{"is"}, {"a"}}, {{{"cool"}}}, \
|
||||
{{"programming"}, {"language!"}}}}|>}};
|
||||
b = a;
|
||||
a[[2]] -= 3;
|
||||
a[[3, 1, 1, 1]] = #^2 &;
|
||||
Print[a];
|
||||
Print[b];
|
||||
1
Task/Deepcopy/Nim/deepcopy-1.nim
Normal file
1
Task/Deepcopy/Nim/deepcopy-1.nim
Normal file
|
|
@ -0,0 +1 @@
|
|||
deepCopy(newObj, obj)
|
||||
34
Task/Deepcopy/Nim/deepcopy-2.nim
Normal file
34
Task/Deepcopy/Nim/deepcopy-2.nim
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
type
|
||||
Node[T] = ref TNode[T]
|
||||
TNode[T] = object
|
||||
data: T
|
||||
left, right: Node[T]
|
||||
|
||||
proc newNode[T](data: T; left, right: Node[T] = nil): Node[T] =
|
||||
Node[T](data: data, left: left, right: right)
|
||||
|
||||
proc preorder[T](n: Node[T]): seq[T] =
|
||||
if n == nil: @[]
|
||||
else: @[n.data] & preorder(n.left) & preorder(n.right)
|
||||
|
||||
var tree = 1.newNode(
|
||||
2.newNode(
|
||||
4.newNode(
|
||||
7.newNode),
|
||||
5.newNode),
|
||||
3.newNode(
|
||||
6.newNode(
|
||||
8.newNode,
|
||||
9.newNode)))
|
||||
|
||||
var tree2: Node[int]
|
||||
tree2.deepCopy tree
|
||||
tree2.data = 10
|
||||
tree2.left.data = 20
|
||||
tree2.right.left.data = 90
|
||||
|
||||
echo "Tree2:"
|
||||
echo preorder tree2
|
||||
|
||||
echo "Tree:"
|
||||
echo preorder tree
|
||||
16
Task/Deepcopy/OCaml/deepcopy-1.ocaml
Normal file
16
Task/Deepcopy/OCaml/deepcopy-1.ocaml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
let rec copy t =
|
||||
if Obj.is_int t then t else
|
||||
let tag = Obj.tag t in
|
||||
if tag = Obj.double_tag then t else
|
||||
if tag = Obj.closure_tag then t else
|
||||
if tag = Obj.string_tag then Obj.repr (String.copy (Obj.obj t)) else
|
||||
if tag = 0 || tag = Obj.double_array_tag then begin
|
||||
let size = Obj.size t in
|
||||
let r = Obj.new_block tag size in
|
||||
for i = 0 to pred size do
|
||||
Obj.set_field r i (copy (Obj.field t i))
|
||||
done;
|
||||
r
|
||||
end else failwith "copy" ;;
|
||||
|
||||
let copy (v : 'a) : 'a = Obj.obj (copy (Obj.repr v))
|
||||
3
Task/Deepcopy/OCaml/deepcopy-2.ocaml
Normal file
3
Task/Deepcopy/OCaml/deepcopy-2.ocaml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
let copy h =
|
||||
{ size = h.size;
|
||||
data = Array.copy h.data }
|
||||
63
Task/Deepcopy/OxygenBasic/deepcopy.basic
Normal file
63
Task/Deepcopy/OxygenBasic/deepcopy.basic
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
'DEEP COPY FOR A RECURSIVE TREE STRUCTURE
|
||||
|
||||
uses console
|
||||
|
||||
class branches
|
||||
'
|
||||
static int count
|
||||
int level
|
||||
int a,b,c
|
||||
branches*branch1
|
||||
branches*branch2
|
||||
'
|
||||
method constructor(int n)
|
||||
=========================
|
||||
level=n
|
||||
count++
|
||||
output count tab level cr
|
||||
if level>0
|
||||
new branches n1(n-1)
|
||||
new branches n2(n-1)
|
||||
@branch1=@n1
|
||||
@branch2=@n2
|
||||
endif
|
||||
...
|
||||
end method
|
||||
'
|
||||
method destructor
|
||||
=================
|
||||
if level>0
|
||||
del branch1
|
||||
del branch2
|
||||
endif
|
||||
...
|
||||
end method
|
||||
'
|
||||
method RecurseCopy(int n, branches *dc, *sc)
|
||||
============================================
|
||||
dc.level=sc.level
|
||||
dc.a=sc.a
|
||||
dc.b=sc.b
|
||||
dc.c=sc.c
|
||||
if n>0
|
||||
RecurseCopy n-1, byval @dc.branch1, byval @sc.branch1
|
||||
RecurseCopy n-1, byval @dc.branch2, byval @sc.branch2
|
||||
endif
|
||||
end method
|
||||
'
|
||||
method DeepCopy() as branches*
|
||||
==============================
|
||||
new branches dc(level)
|
||||
RecurseCopy level,dc,this
|
||||
return @dc
|
||||
end method
|
||||
'
|
||||
end class
|
||||
|
||||
output "count" tab "level" tab "(original)" cr
|
||||
new branches br(3)
|
||||
output "count" tab "level" tab "(copy)" cr
|
||||
branches *bc = br.DeepCopy
|
||||
pause
|
||||
del bc
|
||||
del br
|
||||
21
Task/Deepcopy/PHP/deepcopy-1.php
Normal file
21
Task/Deepcopy/PHP/deepcopy-1.php
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
<?php
|
||||
class Foo
|
||||
{
|
||||
public function __clone()
|
||||
{
|
||||
$this->child = clone $this->child;
|
||||
}
|
||||
}
|
||||
|
||||
$object = new Foo;
|
||||
$object->some_value = 1;
|
||||
$object->child = new stdClass;
|
||||
$object->child->some_value = 1;
|
||||
|
||||
$deepcopy = clone $object;
|
||||
$deepcopy->some_value++;
|
||||
$deepcopy->child->some_value++;
|
||||
|
||||
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";
|
||||
?>
|
||||
14
Task/Deepcopy/PHP/deepcopy-2.php
Normal file
14
Task/Deepcopy/PHP/deepcopy-2.php
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
<?php
|
||||
|
||||
// stdClass is a default PHP object
|
||||
$object = new stdClass;
|
||||
$object->some_value = 1;
|
||||
$object->child = new stdClass;
|
||||
$object->child->some_value = 1;
|
||||
|
||||
$deepcopy = unserialize(serialize($object));
|
||||
$deepcopy->some_value++;
|
||||
$deepcopy->child->some_value++;
|
||||
|
||||
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";
|
||||
11
Task/Deepcopy/Perl/deepcopy.pl
Normal file
11
Task/Deepcopy/Perl/deepcopy.pl
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
#!/usr/bin/perl
|
||||
use strict;
|
||||
use warnings;
|
||||
use Storable;
|
||||
use Data::Dumper;
|
||||
|
||||
my $src = { foo => 0, bar => [0, 1] };
|
||||
$src->{baz} = $src;
|
||||
my $dst = Storable::dclone($src);
|
||||
print Dumper($src);
|
||||
print Dumper($dst);
|
||||
8
Task/Deepcopy/Phix/deepcopy-1.phix
Normal file
8
Task/Deepcopy/Phix/deepcopy-1.phix
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
-->
|
||||
<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>
|
||||
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">a</span>
|
||||
<span style="color: #000000;">b<span style="color: #0000FF;">[<span style="color: #000000;">3<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">4</span>
|
||||
<span style="color: #0000FF;">?<span style="color: #000000;">a</span>
|
||||
<span style="color: #0000FF;">?<span style="color: #000000;">b
|
||||
<!--
|
||||
17
Task/Deepcopy/Phix/deepcopy-2.phix
Normal file
17
Task/Deepcopy/Phix/deepcopy-2.phix
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
-->
|
||||
<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>
|
||||
<span style="color: #008080;">if</span> <span style="color: #004080;">atom<span style="color: #0000FF;">(<span style="color: #000000;">o<span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
|
||||
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">o</span>
|
||||
<span style="color: #008080;">else</span>
|
||||
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat<span style="color: #0000FF;">(<span style="color: #008000;">' '<span style="color: #0000FF;">,<span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">o<span style="color: #0000FF;">)<span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">o<span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #000000;">res<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">deep_copy<span style="color: #0000FF;">(<span style="color: #000000;">o<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]<span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
|
||||
|
||||
<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
|
||||
<!--
|
||||
5
Task/Deepcopy/Phix/deepcopy-3.phix
Normal file
5
Task/Deepcopy/Phix/deepcopy-3.phix
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
-->
|
||||
<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
|
||||
<!--
|
||||
1
Task/Deepcopy/PicoLisp/deepcopy-1.l
Normal file
1
Task/Deepcopy/PicoLisp/deepcopy-1.l
Normal file
|
|
@ -0,0 +1 @@
|
|||
(mapcar copy List)
|
||||
4
Task/Deepcopy/PicoLisp/deepcopy-2.l
Normal file
4
Task/Deepcopy/PicoLisp/deepcopy-2.l
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
(de deepCopy (X)
|
||||
(if (atom X)
|
||||
X
|
||||
(cons (deepCopy (car X)) (deepCopy (cdr X))) ) )
|
||||
25
Task/Deepcopy/PicoLisp/deepcopy-3.l
Normal file
25
Task/Deepcopy/PicoLisp/deepcopy-3.l
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
: (setq A '((a . b) (c d e) f g . e))
|
||||
-> ((a . b) (c d e) f g . e)
|
||||
|
||||
: (setq B (deepCopy A))
|
||||
-> ((a . b) (c d e) f g . e)
|
||||
|
||||
: A
|
||||
-> ((a . b) (c d e) f g . e)
|
||||
|
||||
: B
|
||||
-> ((a . b) (c d e) f g . e)
|
||||
|
||||
: (= A B)
|
||||
-> T # A and its copy B are structure-equal
|
||||
: (== A B)
|
||||
-> NIL # but they are not identical (pointer-equal)
|
||||
|
||||
: (cadr A)
|
||||
-> (c d e)
|
||||
|
||||
: (cadr B)
|
||||
-> (c d e)
|
||||
|
||||
: (== (cadr A) (cadr B))
|
||||
-> NIL # The same holds for sub-structures
|
||||
11
Task/Deepcopy/PicoLisp/deepcopy-4.l
Normal file
11
Task/Deepcopy/PicoLisp/deepcopy-4.l
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
(de deepCopy (X)
|
||||
(let Mark NIL
|
||||
(recur (X)
|
||||
(cond
|
||||
((atom X) X)
|
||||
((asoq X Mark) (cdr @))
|
||||
(T
|
||||
(prog1 (cons)
|
||||
(push 'Mark (cons X @))
|
||||
(set @ (recurse (car X)))
|
||||
(con @ (recurse (cdr X))) ) ) ) ) ) )
|
||||
12
Task/Deepcopy/PicoLisp/deepcopy-5.l
Normal file
12
Task/Deepcopy/PicoLisp/deepcopy-5.l
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
: (setq A '(a b .) B (deepCopy A))
|
||||
-> (a b .)
|
||||
: A
|
||||
-> (a b .)
|
||||
: B
|
||||
-> (a b .)
|
||||
|
||||
: (= A B)
|
||||
-> T # A and its copy B are structure-equal
|
||||
|
||||
: (== A B)
|
||||
-> NIL # but they are not identical (pointer-equal)
|
||||
38
Task/Deepcopy/PureBasic/deepcopy.basic
Normal file
38
Task/Deepcopy/PureBasic/deepcopy.basic
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
Macro PrintStruc(StrucVal)
|
||||
PrintN(Str(StrucVal#\value1))
|
||||
PrintN(Chr(StrucVal#\value2))
|
||||
PrintN(StrucVal#\value3)
|
||||
If StrucVal#\value4
|
||||
PrintN("TRUE")
|
||||
Else
|
||||
PrintN("FALSE")
|
||||
EndIf
|
||||
PrintN("")
|
||||
EndMacro
|
||||
|
||||
Structure TTypeA
|
||||
value1.i
|
||||
value2.c
|
||||
value3.s[10]
|
||||
value4.b
|
||||
EndStructure
|
||||
|
||||
Define.TTypeA a, b
|
||||
|
||||
a\value1=10
|
||||
a\value2='A'
|
||||
a\value3="OK"
|
||||
a\value4=#True
|
||||
|
||||
b=a
|
||||
|
||||
a\value1=20
|
||||
a\value2='B'
|
||||
a\value3="NOK"
|
||||
a\value4=#False
|
||||
|
||||
If OpenConsole("")
|
||||
PrintN("Value of 'a':") : PrintStruc(a)
|
||||
PrintN("Value of 'b':") : PrintStruc(b)
|
||||
Input()
|
||||
EndIf
|
||||
2
Task/Deepcopy/Python/deepcopy.py
Normal file
2
Task/Deepcopy/Python/deepcopy.py
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import copy
|
||||
deepcopy_of_obj = copy.deepcopy(obj)
|
||||
14
Task/Deepcopy/Racket/deepcopy.rkt
Normal file
14
Task/Deepcopy/Racket/deepcopy.rkt
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
#lang racket
|
||||
|
||||
(define (deepcopy x)
|
||||
;; make sure that all sharings are shown
|
||||
(parameterize ([print-graph #t]) (read (open-input-string (format "~s" x)))))
|
||||
|
||||
(define (try x)
|
||||
;; use the same setting to see that it worked
|
||||
(parameterize ([print-graph #t])
|
||||
(printf "original: ~s\n" x)
|
||||
(printf "deepcopy: ~s\n" (deepcopy x))
|
||||
;; print both also, which shows that they are indeed different
|
||||
(printf "both: ~s\n" (list x (deepcopy x)))))
|
||||
(try (shared ([x (cons 1 x)]) (list x x)))
|
||||
6
Task/Deepcopy/Raku/deepcopy-1.raku
Normal file
6
Task/Deepcopy/Raku/deepcopy-1.raku
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
my %x = foo => 0, bar => [0, 1];
|
||||
my %y = %x.deepmap(*.clone);
|
||||
|
||||
%x<bar>[1]++;
|
||||
say %x;
|
||||
say %y;
|
||||
6
Task/Deepcopy/Raku/deepcopy-2.raku
Normal file
6
Task/Deepcopy/Raku/deepcopy-2.raku
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
my %x = foo => 0, bar => [0, 1];
|
||||
my %y = %x.raku.EVAL;
|
||||
|
||||
%x<bar>[1]++;
|
||||
say %x;
|
||||
say %y;
|
||||
22
Task/Deepcopy/Ruby/deepcopy.rb
Normal file
22
Task/Deepcopy/Ruby/deepcopy.rb
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
# _orig_ is a Hash that contains an Array.
|
||||
orig = { :num => 1, :ary => [2, 3] }
|
||||
orig[:cycle] = orig # _orig_ also contains itself.
|
||||
|
||||
# _copy_ becomes a deep copy of _orig_.
|
||||
copy = Marshal.load(Marshal.dump orig)
|
||||
|
||||
# These changes to _orig_ never affect _copy_,
|
||||
# because _orig_ and _copy_ are disjoint structures.
|
||||
orig[:ary] << 4
|
||||
orig[:rng] = (5..6)
|
||||
|
||||
# Because of deep copy, orig[:ary] and copy[:ary]
|
||||
# refer to different Arrays.
|
||||
p orig # => {:num=>1, :ary=>[2, 3, 4], :cycle=>{...}, :rng=>5..6}
|
||||
p copy # => {:num=>1, :ary=>[2, 3], :cycle=>{...}}
|
||||
|
||||
# The original contains itself, and the copy contains itself,
|
||||
# but the original and the copy are not the same object.
|
||||
p [(orig.equal? orig[:cycle]),
|
||||
(copy.equal? copy[:cycle]),
|
||||
(not orig.equal? copy)] # => [true, true, true]
|
||||
27
Task/Deepcopy/Rust/deepcopy.rust
Normal file
27
Task/Deepcopy/Rust/deepcopy.rust
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
// The compiler can automatically implement Clone on structs (assuming all members have implemented Clone).
|
||||
#[derive(Clone)]
|
||||
struct Tree<T> {
|
||||
left: Leaf<T>,
|
||||
data: T,
|
||||
right: Leaf<T>,
|
||||
}
|
||||
|
||||
type Leaf<T> = Option<Box<Tree<T>>>;
|
||||
|
||||
impl<T> Tree<T> {
|
||||
fn root(data: T) -> Self {
|
||||
Self { left: None, data, right: None }
|
||||
}
|
||||
|
||||
fn leaf(d: T) -> Leaf<T> {
|
||||
Some(Box::new(Self::root(d)))
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut tree = Tree::root([4, 5, 6]);
|
||||
tree.right = Tree::leaf([1, 2, 3]);
|
||||
tree.left = Tree::leaf([7, 8, 9]);
|
||||
|
||||
let newtree = tree.clone();
|
||||
}
|
||||
49
Task/Deepcopy/Scheme/deepcopy.ss
Normal file
49
Task/Deepcopy/Scheme/deepcopy.ss
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
(define (deep-copy-1 exp)
|
||||
;; basic version that copies an arbitrary tree made up of pairs
|
||||
(cond ((pair? exp)
|
||||
(cons (deep-copy-1 (car exp))
|
||||
(deep-copy-1 (cdr exp))))
|
||||
;; cases for extra container data types can be
|
||||
;; added here, like vectors and so on
|
||||
(else ;; atomic objects
|
||||
(if (string? exp)
|
||||
(string-copy exp)
|
||||
exp))))
|
||||
|
||||
(define (deep-copy-2 exp)
|
||||
(let ((sharing (make-hash-table)))
|
||||
(let loop ((exp exp))
|
||||
(cond ((pair? exp)
|
||||
(cond ((get-hash-table sharing exp #f)
|
||||
=> (lambda (copy)
|
||||
copy))
|
||||
(else
|
||||
(let ((res (cons #f #f)))
|
||||
(put-hash-table! sharing exp res)
|
||||
(set-car! res (loop (car exp)))
|
||||
(set-cdr! res (loop (cdr exp)))
|
||||
res))))
|
||||
(else
|
||||
(if (string? exp)
|
||||
(string-copy exp)
|
||||
exp))))))
|
||||
|
||||
(define t1 '(a b c d))
|
||||
(define t2 (list #f))
|
||||
(set-car! t2 t2)
|
||||
(define t2b (list #f))
|
||||
(set-car! t2b t2b)
|
||||
(define t3 (list #f #f))
|
||||
(set-car! t3 t3)
|
||||
(set-car! (cdr t3) t3)
|
||||
(define t4 (list t2 t2b))
|
||||
|
||||
;> (print-graph #t)
|
||||
;> (deep-copy-2 t1)
|
||||
;(a b c d)
|
||||
;> (deep-copy-2 t2)
|
||||
;#0=(#0#)
|
||||
;> (deep-copy-2 t3)
|
||||
;#0=(#0# #0#)
|
||||
;> (deep-copy-2 t4)
|
||||
;(#0=(#0#) #1=(#1#))
|
||||
15
Task/Deepcopy/Sidef/deepcopy.sidef
Normal file
15
Task/Deepcopy/Sidef/deepcopy.sidef
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
var src = Hash(foo => 0, bar => [0,1])
|
||||
|
||||
# Add a cyclic reference
|
||||
src{:baz} = src
|
||||
|
||||
# Make a deep clone
|
||||
var dst = src.dclone
|
||||
|
||||
# The address of src
|
||||
say src.object_id
|
||||
say src{:baz}.object_id
|
||||
|
||||
# The address of dst
|
||||
say dst.object_id
|
||||
say dst{:baz}.object_id
|
||||
1
Task/Deepcopy/Tcl/deepcopy-1.tcl
Normal file
1
Task/Deepcopy/Tcl/deepcopy-1.tcl
Normal file
|
|
@ -0,0 +1 @@
|
|||
set deepCopy [string range ${valueToCopy}x 0 end-1]
|
||||
1
Task/Deepcopy/Tcl/deepcopy-2.tcl
Normal file
1
Task/Deepcopy/Tcl/deepcopy-2.tcl
Normal file
|
|
@ -0,0 +1 @@
|
|||
set copiedObject [oo::copy $originalObject]
|
||||
41
Task/Deepcopy/Wren/deepcopy.wren
Normal file
41
Task/Deepcopy/Wren/deepcopy.wren
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import "/trait" for Cloneable, CloneableSeq
|
||||
import "/seq" for Lst
|
||||
|
||||
class MyMap is Cloneable {
|
||||
construct new (m) {
|
||||
if (m.type != Map) Fiber.abort("Argument must be a Map.")
|
||||
_m = m
|
||||
}
|
||||
|
||||
m { _m }
|
||||
|
||||
toString { _m.toString }
|
||||
|
||||
clone() {
|
||||
// Map keys are always immutable built-in types so we only need to worry about
|
||||
// their values which can be anything.
|
||||
var m2 = {}
|
||||
for (me in _m) {
|
||||
var v = me.value
|
||||
m2[me.key] = (v is List) ? Lst.clone(v) :
|
||||
(v is Cloneable || v is CloneableSeq) ? v.clone() : v
|
||||
}
|
||||
return MyMap.new(m2)
|
||||
}
|
||||
}
|
||||
|
||||
var my = MyMap.new({"a": 0, "b": 1, "c": [2, 3], "d": MyMap.new({"e": 4})})
|
||||
var my2 = my.clone()
|
||||
System.print("Before any changes:")
|
||||
System.print(" my = %(my)")
|
||||
System.print(" my2 = %(my2)")
|
||||
// now change my2
|
||||
my2.m["a"] = 5
|
||||
my2.m["b"] = 6
|
||||
my2.m["c"][0] = 7
|
||||
my2.m["c"][1] = 8
|
||||
my2.m["d"].m["e"] = 9
|
||||
my2.m["d"].m["f"] = 10
|
||||
System.print("\nAfter changes to my2:")
|
||||
System.print(" my = %(my)")
|
||||
System.print(" my2 = %(my2)")
|
||||
2
Task/Deepcopy/Z80-Assembly/deepcopy-1.z80
Normal file
2
Task/Deepcopy/Z80-Assembly/deepcopy-1.z80
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
LD HL,(&C000)
|
||||
LD (&D000),HL
|
||||
10
Task/Deepcopy/Z80-Assembly/deepcopy-2.z80
Normal file
10
Task/Deepcopy/Z80-Assembly/deepcopy-2.z80
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
LD HL,MyString
|
||||
LD DE,UserRam
|
||||
LD BC,MyString_End-MyString ;the difference between these two addresses is the byte count.
|
||||
LDIR ;essentially C's memcpy()
|
||||
|
||||
MyString:
|
||||
byte "Hello, world!",0
|
||||
|
||||
UserRam:
|
||||
ds 32,0 ;32 bytes of memory initialized to zero.
|
||||
Loading…
Add table
Add a link
Reference in a new issue