Copying Data

In the course of writing software, it can be very common that you'll need to copy some data. In particular, when dealing with collections that are either themselves mutable, or contain mutable elements, copying can be needed so that one copy of the data can be updated while leaving the other unchanged.

However, you may find that many languages (e.g. Java/C++) make this extremely simple task prohibitively difficult requiring planning ahead to explicitly implement copying support on every data type that you think you'll want to copy in the future. To address this, Claro supports deep copying out-of-the-box with the builtin copy(...) function.

Fig 1:


var l = mut [1, 2, 3];
var myCopy = copy(l);

print("Before update:");
print("l:      {l}");
print("myCopy: {myCopy}");

myCopy[2] = -99999;

print("\nAfter update:");
print("l:      {l}");
print("myCopy: {myCopy}");

Output:

Before update:
l:      mut [1, 2, 3]
myCopy: mut [1, 2, 3]

After update:
l:      mut [1, 2, 3]
myCopy: mut [1, 2, -99999]

Deep Copying

Claro's builtin copy(...) function performs a deep copy, meaning that the entire nested structure is traversed and copied (as needed). The below example copies some nested data and demonstrates that the resulting internal data can be mutated in isolation:

Fig 2:


var original = {left = mut (1, [10]), right = (["aaa"], mut ["bbb"])};
var copied = copy(original);

print(original);
print(copied);
print("");

copied.left[0] = -99;
copied.right[1][0] = "MODIFIED";

print(original);
print(copied);
print("");

Output:

[0.003s][warning][perf,memops] Cannot use file /tmp/hsperfdata_runner/6 because it is locked by another process (errno = 11)
{left = mut (1, [10]), right = ([aaa], mut [bbb])}
{left = mut (1, [10]), right = ([aaa], mut [bbb])}

{left = mut (1, [10]), right = ([aaa], mut [bbb])}
{left = mut (-99, [10]), right = ([aaa], mut [MODIFIED])}