Deepcopy: Difference between revisions

Replace #Erlang content
m (→‎{{header|Phix}}: and one tenth incompatible)
(Replace #Erlang content)
Line 585:
 
=={{header|Erlang}}==
 
Until somebody explains how to create cyclic data structures in Erlang I can show heterogeneous data.
All values in Erlang are immutable and garbage collected, so copying is meaningless. Moreover, it's impossible to create cyclic data structures in Erlang, due to the absence of a <code>let rec</code> construct (and the fact that all values are immutable).
 
Data is copied when sent from one Erlang (lightweight) processes to another, because each process manages it's own memory. This is an implementation detail and is not part of the language semantics.
 
An exception is "large binaries", which can be shared between Erlang processes, and sub-binaries which can reference larger binaries. These can be copied using <code>binary:copy/1</code> to free the memory of the referenced larger binary if it has no other references. This function is provided with [https://www.erlang.org/doc/man/binary.html#copy-1 a note in the reference manual] indicating that this is usually not what you want. Here is an example though:
 
{{out}}
<pre>
1> A = <<"abcdefghijklmnopqrstuvwxyz">>.
16> D.
<<"abcdefghijklmnopqrstuvwxyz">>
{dict,4,16,16,8,80,48,
2> B = <<A/binary, A/binary, A/binary, A/binary>>.
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
<<"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz">>
{{[["qwe",49,50,51],[p|<0.32.0>]],
3> <<_:10/binary, C:80/binary, _/binary>> = B.
[[a|b]],
<<"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz">>
[],[],[],[],[],[],[],[],[],
164> DC.
[[1|2]],
<<"klmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl">>
[],[],[],[]}}}
5> byte_size(C).
[],[],[],[],[],[],[],[],[],
80
[[1|2]],
6> binary:referenced_byte_size(C).
[],[],[],[]}}}
104
17> D2 = D.
7> C2 = binary:copy(C).
18> D2.
<<"klmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl">>
{dict,4,16,16,8,80,48,
178> D2C2 == DC.
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
true
{{[["qwe",49,50,51],[p|<0.32.0>]],
9> binary:referenced_byte_size(C2).
[[a|b]],
80
[],[],[],[],[],[],[],[],[],
[[1|2]],
[],[],[],[]}}}
</pre>