APLX Help : Help on APL language : System Methods : ⎕CLONE Create copies of object
|
|
|
|
|
Implemented for Internal and External classes. Not implemented for System classes. Syntax:
The monadic system method In this example, we create a simple class Point, and create an instance of it. The instance is then cloned four times. Note that the four copies are independent objects; changing a property of one of them does not affect the others: 'Point' ⎕IC ⎕BOX 'X Y Z'
1 1 1
PT←⎕NEW 'Point'
PT.X←34 ⋄ PT.Y←23 ⋄ PT.Z←12
VEC←PT.⎕CLONE 4
VEC
[Point] [Point] [Point] [Point]
VEC.X
34 34 34 34
VEC[1].X←11
VEC.X
11 34 34 34
Contrast this with the following example, in which VEC2 contains four references to the same object: VEC2←4⍴PT
VEC2.X
34 34 34 34
VEC2[1].X←11
VEC2.X
11 11 11 11
When cloning internal objects, if the properties of the original object contain further object references these sub-objects are not cloned; instead, both the original and cloned objects will point to the same original sub-objects. This is known as a 'shallow' copy operation. If an object contains file handles or database references, cloning it in this way may not make sense. On the other hand, for simple objects it can be a very useful way of rapidly creating new instances with an initial set of known properties.
.NetIn the .Net architecture, JavaFor Java classes, In this example, we create an instance of the Java Date class (which defaults to the current date/time), clone 12 copies of it, and set the month of each copy to a different value: date←'java' ⎕NEW 'java.util.Date'
date
[java:Date]
dateList←date.⎕CLONE 12
dateList.setMonth ((⍳12)-⎕IO)
12 1⍴dateList.⎕DS
Wed Jan 10 14:33:12 GMT 2007
Sat Feb 10 14:33:12 GMT 2007
Sat Mar 10 14:33:12 GMT 2007
Tue Apr 10 14:33:12 BST 2007
Thu May 10 14:33:12 BST 2007
Sun Jun 10 14:33:12 BST 2007
Tue Jul 10 14:33:12 BST 2007
Fri Aug 10 14:33:12 BST 2007
Mon Sep 10 14:33:12 BST 2007
Wed Oct 10 14:33:12 BST 2007
Sat Nov 10 14:33:12 GMT 2007
Mon Dec 10 14:33:12 GMT 2007
R
c←'r' ⎕new 'complex' 2 3
c
[r:complex]
c.⎕ds
2+3i
t←c.⎕clone 5
t.⎕ds
2+3i 2+3i 2+3i 2+3i 2+3i
t
[r:complex] [r:complex] [r:complex] [r:complex] [r:complex]
Ruby
In this example, we create a Ruby array (referenced by A), and place three strings in it. We then make a clone of it (referenced by B), which creates an independent copy of the array. Therefore, when we add a fourth element to the array referenced by A, the copy is unchanged: A←'ruby' ⎕NEW 'Array'
dummy←A.push 'First'
dummy←A.push 'Second'
dummy←A.push 'Third'
A.length
3
A.⎕VAL
First Second Third
B←A.⎕CLONE 1
B.length
3
B.⎕VAL
First Second Third
dummy←A.push 'Fourth'
A.length
4
A.⎕VAL
First Second Third Fourth
B.length
3
B.⎕VAL
First Second Third
|
|
APLX Help : Help on APL language : System Methods : ⎕CLONE Create copies of object
|
|
Copyright © 1996-2010 MicroAPL Ltd