The standard librarySlide 48 of 86
48MapThe standard library
Maps
hive.map.Map<K, T> is the one collection that is not a vector. A key is compared and hashed whole, so it is a Str, Int, Float, Bool, Atom, or a declared type whose fields are all one of those. new() says only "empty", so it takes its type from where it lands — a declaration, a return, or a parameter — or, bound with :=, from the first later use that says it, such as set(m, "a", 1), and keeps it.
set(m, key, value)anddelete(m, key)areprocs that take the mapmut. Replacing a value keeps its key's place; deleting a key and setting it again moves it to the end.plus(m, key, value)andminus(m, key)do the same but answer with a new map and leavemas it was, somneeds nomut.get(m, key)answers with aResultwhoseErrorcarriesfalse;has(m, key)asks the same without the value.keys(m)andvalues(m)are fresh vectors in the order the keys were set, so echoing a map prints the same on every run.fromTable(t)andtoTable(m)convert between a map ofStrtoStrand aTableof two-cell rows.fromTableskips a row with fewer than two cells, and a key given twice keeps its first place and its last value.
A map is not indexed or walked: m[0] and for each … in m are compile errors; walk keys(m) instead. The module is map for short — map.keys(m) — and the builtin map(values, f) is still there: map. and a name is the module, a bare map(…) the builtin. A map cannot be encoded or sent to a service; send its pairs as a vector of a type declared for them.
Setting, getting and walking
proc main(): void {
mut hive.map.Map<Str, Int> counts = hive.map.new()
hive.map.set(counts, "bees", 12)
hive.map.set(counts, "hives", 3)
if hive.map.get(counts, "bees") is Result.Ok(n) {
echo n
}
echo hive.map.has(counts, "wasps")
hive.map.delete(counts, "hives")
echo hive.map.keys(counts)
echo hive.map.values(counts)
echo hive.map.plus(counts, "wasps", 2)
echo counts
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
Crossing to and from a Table
proc main(): void {
mut hive.map.Map<Str, Str> labels = hive.map.new()
hive.map.set(labels, "bees", "many")
echo hive.map.toTable(labels)
echo hive.map.get(hive.map.fromTable([["wasps", "few"]]), "wasps")
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
Output
Run a program to see what it prints here.