module Maps {
// MAP BASICS
fn test() {
// maps can hold different types. maps are immutable by default. see the section
// on mutability for more info on mutable maps.
let x1 = {"a" : 1, "b" : 2};
// the type of a map is Map{key,val}
let x2 : Map{string, int} = {"a" : 1, "b" : 2};
// there are various functions manipulate the map and return a copy with the updates
let x3 = x1.merge({"c" : 3});
// the number of elements in the map is accessed using #
let x5 = x1#; // 3
// individual elements are accessed using [], using the key
let x7 = x1["a"]; // 1
// map accesses when the key is not present will throw
let x9 = x1["z"]; // throws
// the get method allows a default value to be specified
let x11 = x1.get("z", 0); // 0
// maps allow iteration, which produce a tuple of (key, value)
for ((k,v) in x2) {
print(k, v); // prints keys and values
}
// use .keys to iterate just the keys
for (key in x2.keys) {
print(key); // prints keys
}
// use .values to iterate just the values
for (val in x2.values) {
print(val); // prints values
}
// maps can be constructed from iterators of tuple (key,val)
let x13 = {...x1, ...x2, ...{"z" : 26}, ...[("y", 25)]};
}
}