Mutation and copying
A binding holds a value. Some builtins change the value a binding holds without
an assignment, which is why push(xs, x); is a statement and not xs = push(...).
This page lists exactly which ones do that, what each one answers, and the one
place where the reference and the runtime disagree.
Which builtins change their argument
| builtin | what it changes | what it answers |
|---|---|---|
push(xs, x) |
adds x to the end of the list |
nothing |
set_at(xs, i, v) |
replaces the element at i |
nothing |
sort(xs) |
orders the list in place | nothing |
remove_at(xs, i) |
takes the element at i out |
the element it removed |
put(m, k, v) |
adds or replaces one key | the map |
del(m, k) |
removes one key | the map |
The first three answer nothing, so using their result is a diagnostic (E0260)
rather than a value. remove_at, put and del answer something, so their
result can be used or ignored.
let xs = ["b", "a"];
sort(xs);
print(str(xs));
let gone = remove_at(xs, 0);
print(gone);
print(str(xs));
let m = {"pages": 412};
put(m, "read", true);
print(str(keys(m)));
["a","b"]
a
["b"]
["pages","read"]Using the answer of a builtin that has none is an error, not a silent void:
let xs = [1];
let r = push(xs, 2);
E0260
Assignment copies
let b = a; copies the value. Changing b afterwards leaves a alone, so a
list or a map cannot be changed through another binding by accident.
let u = [1];
let v = u;
push(v, 2);
print(str(u));
print(str(v));
let m = {"a": 1};
let n = m;
put(n, "b", 2);
print(str(keys(m)));
print(str(keys(n)));
[1]
[1,2]
["a"]
["a","b"]The rule to hold on to: a builtin changes the value behind the name you pass it. It never changes a copy that another binding holds.
Where the reference and the runtime disagree
midad spec --json reports mutates: false for put and del. The runtime
does not agree: both change the map they are given, and both answer that same
map, which is why m = put(m, k, v); is harmless rather than necessary. The
builtins reference is generated from midad spec,
so it carries no mutation marker on those two rows; the table above is what
midad run does.
Next: functions.