Maps in Scilab
Maps are Scilab’s built-in associative data type (sometimes called hashes or dicts in other languages).
To create an empty map, use the mlist
function.
m = mlist(['keys', 'vals'], [], []);
Set key/value pairs using typical name(key) = val
syntax.
m.keys($ + 1) = 'k1';
m.vals($ + 1) = 7;
m.keys($ + 1) = 'k2';
m.vals($ + 1) = 13;
Printing a map with disp
will show all of its key/value pairs.
disp(m);
Get a value for a key with its index.
index = find(m.keys == 'k1');
v1 = m.vals(index);
disp('v1: ' + string(v1));
If the key doesn’t exist, the zero value (e.g., 0
for integers) of the value type is returned.
index = find(m.keys == 'k3');
if isempty(index) then
v3 = 0;
else
v3 = m.vals(index);
end
disp('v3: ' + string(v3));
The size
function returns the number of key/value pairs when called on a map.
len = length(m.keys);
disp('len: ' + string(len));
To remove key/value pairs from a map, use appropriate indexing.
index = find(m.keys == 'k2');
m.keys(index) = [];
m.vals(index) = [];
disp(m);
To remove all key/value pairs from a map, simply clear the lists.
m.keys = [];
m.vals = [];
disp(m);
The second return value when getting a value from a map indicates if the key was present in the map.
index = find(m.keys == 'k2');
prs = ~isempty(index);
disp('prs: ' + string(prs));
You can also declare and initialize a new map in the same line with this syntax.
n = mlist(['keys', 'vals'], ['foo', 'bar'], [1, 2]);
disp(n);
Note that maps appear in the form [keys:values]
when printed with disp
.
if equals(n.vals, [1, 2]) then
disp('n == n2');
end
--> disp(m)
keys: ["k1" "k2"]
vals: [7 13]
--> disp('v1: ' + string(v1))
v1: 7
--> disp('v3: ' + string(v3))
v3: 0
--> disp('len: ' + string(len))
len: 2
--> disp(m)
keys: ["k1"]
vals: [7]
--> disp(m)
keys: []
vals: []
--> disp('prs: ' + string(prs))
prs: F
--> disp(n)
keys: ["foo" "bar"]
vals: [1 2]
--> disp('n == n2')
n == n2