LEVIATHAN vd52e79c4 · d52e79c486

Standard Library

class Map<K, V>

An associative collection from keys of type K to values of type V, with value semantics.

since 0.1.0-alpha.1linuxwindowswasm

bases
IIterable<Pair<K, V>>

Overview

Like Array, a map is never changed in place: with and without return a new map, and the index assignment m[k] = v rebinds the variable to an updated copy. Entries keep the order in which their keys were first added, and keys, values, entries and for loops all follow that order. Updating the value of an existing key does not move it.

Keys are compared by value for numbers, strings and bool, field by field for structs, and by identity for class instances. Read a value with m[k] or at, which throw when the key is missing; use has, atOrNone or atOr when it might be. for (Pair<K, V> e in m) visits the entries as pairs with first (the key) and second (the value). Printing a map with console.writeln shows it as {key: value, ...}.

Description

Map<K, V> associates keys with values. Like Array, it is a value: two names never share one map. Its methods come in two families. The imperative ones mutate the map they are called on and return nothing: set(key, value) adds or replaces, remove(key) removes, clear() empties. The prepositional ones are pure and return a new map: with(key, value) and without(key). Because get is a keyword, at reads. The bracket form m[k] = v stores into the map in place, and m[k] reads like m.at(k).

This changes behaviour for existing programs. m = m.with(k, v) still compiles and is still pure, but the idiom for change is now the statement m.set(k, v);; a statement that discards the result of with or without is a warning that names the twin. A verb's value cannot be used, and the arguments of a verb are evaluated before the map's current value is read.

Create an empty map with Map(), or with a declaration that has no initializer, Map<string, int> m;. A map prints as {a: 1, b: 2}.

Order. A map remembers insertion order. keys(), values(), entries(), a for loop and printing all follow it. Replacing the value of a key that is already present keeps the key where it was. Removing a key and adding it again moves it to the end.

Key equality. Every type can be a key. Primitive keys (int, string, bool, ...) compare by value, floats canonically (-0.0 and 0.0 are one key, and so is every NaN), and values of different numeric types never match: in a Map<int | byte, V>, byte 1 and int 1 are different keys (a Map<int, V> converts a byte argument to int first). A literal key takes the key type, in an index as in an argument: in a Map<byte?, V>, m[1] and m.has(1) are the byte key 1. A struct key compares field by field, so two separately built Pt(1, 2) values are the same key. An Array key compares element by element in order, a Map or Set key by content regardless of order. A class key and a function value compare by identity: two distinct objects are different keys even when their fields match.

Equality. m1 == m2 is true when both maps hold the same keys with equal values, whatever the order in which they were added.

Missing keys. at(k) and m[k] throw RuntimeException (with the message key not found: ...) when the key is absent. Use has(k) to test, atOrNone(k) to get a V?, or atOr(k, fallback) to get a default.

Iteration. for (Pair<K, V> e in m) (or for (var e in m)) visits each entry as a Pair<K, V>, with the key in e.first and the value in e.second, in insertion order. entries() returns the same pairs as an Array.

Building, reading and iterating a map

use io::console;

Map<string, int> m = Map();
m.set("b", 2); m.set("a", 1); m.set("c", 3);
console.writeln(m);
m.set("b", 20);
console.writeln(m);
m.remove("a");
console.writeln(m);
console.writeln(m.keys());
console.writeln(m.values());
console.writeln(m.has("c"));
console.writeln(m.length());
console.writeln(m.atOr("zz", -1));
console.writeln(m.atOrNone("zz") == None);
console.writeln(m.atOrNone("c"));
m["d"] = 4;
for (var e in m) { console.writeln("${e.first}=${e.second}"); }
console.writeln(m);
{b: 2, a: 1, c: 3}
{b: 20, a: 1, c: 3}
{b: 20, c: 3}
[b, c]
[20, 3]
true
2
-1
true
3
b=20
c=3
d=4
{b: 20, c: 3, d: 4}

Rules

  • set, remove and clear mutate the place they are called on and return nothing; with and without are pure and return a new map. See lang.collection-value-semantics.
  • m[k] = v stores into the variable's own map; no other holder sees it.
  • Iteration, keys, values and entries follow insertion order. Replacing a value keeps its key's position; a removed and re-added key goes to the end.
  • Struct keys are equal field by field; class keys are equal only when they are the same object.
  • at and m[k] throw on a missing key; atOrNone and atOr do not.
  • withAll(other) adds every entry of other, mapValues(f) transforms the values and keeps the keys, and whereEntries(pred) keeps the entries for which pred(key, value) is true. Each returns a new map.

Examples

Struct keys, class keys and bulk operations

use io::console;

struct Pt { int x; int y; }
class Tag { string n; }
Map<Pt, string> byPoint = Map();
byPoint.set(Pt(1, 2), "a"); byPoint.set(Pt(1, 2), "b"); byPoint.set(Pt(3, 4), "c");
console.writeln(byPoint.length());
console.writeln(byPoint.at(Pt(1, 2)));
Tag t1 = Tag("k");
Tag t2 = Tag("k");
Map<Tag, int> byTag = Map();
byTag.set(t1, 1); byTag.set(t2, 2); byTag.set(t1, 3);
console.writeln(byTag.length());
console.writeln(byTag.at(t1));
Map<string, int> a = Map();
a.set("x", 1); a.set("y", 2); a.set("z", 3);
console.writeln(a.mapValues((v) => v * 10));
console.writeln(a.whereEntries((k, v) => v > 1));
Map<string, int> extra = Map();
extra.set("z", 0); extra.set("w", 9);
console.writeln(a.withAll(extra));
console.writeln(a.entries().length());
Map<int, string> im = Map();
im.set(5, "five"); im.set(1, "one"); im.remove(5); im.set(5, "again");
console.writeln(im);
2
b
2
3
{x: 10, y: 20, z: 30}
{y: 2, z: 3}
{x: 1, y: 2, z: 0, w: 9}
3
{1: one, 5: again}

Array keys

use io::console;

Map<Array<int>, string> byPath = Map();
byPath[[1, 2]] = "first";
Array<int> path = [1];
path.add(2);
byPath[path] = "again";
console.writeln(byPath.length());
console.writeln(byPath[[1, 2]]);
console.writeln(byPath.has([2, 1]));
1
again
false

A missing key throws

use io::console;

Map<string, int> ages = Map();
ages.set("ann", 30);
try {
    console.writeln(ages.at("bob"));
} catch (RuntimeException e) {
    console.writeln(e.message);
}
try {
    console.writeln(ages["cy"]);
} catch (RuntimeException e) {
    console.writeln(e.message);
}
console.writeln(ages.has("bob") ? ages["bob"] : -1);
key not found: bob
key not found: cy
-1

Notes

A map stored in a class field is a place like any other: index.set(k, v);. An Array.groupBy call returns a Map from each key to the array of elements that produced it.

A lookup (m[k], has, at, atOr) is O(1) expected on every engine. On LLVM and on the IR interpreter (--ir), m[k] = v, m.set(k, v) and m.remove(k) on a map that only a local variable holds are amortized O(1): the map is updated in place. A map that something else also holds (another variable, a field, a container, a running loop) is copied first, so the other holder never sees the change. A map in a field or a top-level variable can be copied by an update even when nothing else holds it — g = g.with(k, v) on a top-level variable always is (the verb form g.set(k, v) is not). The reference interpreter (--run) copies the map on every update. A removed key that is added again goes to the end of the insertion order.

Examples

Counting words

use io::console;

Map<string, int> counts = Map();
for (string w in ["a", "b", "a", "c", "a"]) {
    counts[w] = counts.atOr(w, 0) + 1;
}
console.writeln(counts);
console.writeln(counts.length());
for (Pair<string, int> e in counts) {
    console.writeln("${e.first} -> ${e.second}");
}
{a: 3, b: 1, c: 1}
3
a -> 3
b -> 1
c -> 1

Constructors

new

new()

Create an empty map.

Map<string, int> m; with no initializer is the same empty map.

Examples

An empty map

use io::console;

Map<string, int> m = Map();
console.writeln(m.length());
m["x"] = 1;
console.writeln(m);
0
{x: 1}

Accessors

[]

get [](K key) -> V

The value stored under key, written m[key].

Assigning to a key, m[key] = val, rebinds the variable to an updated copy of the map (the same result as with); other variables that held the old map still see the old value.

Parameters

key
The key to look up.

Throws

RuntimeException
when the map has no entry for key.

Examples

Indexing and index assignment

use io::console;

Map<string, int> a = Map();
a["x"] = 1;
Map<string, int> b;
b = a;
b["x"] = 2;
console.writeln(a["x"]);
console.writeln(b["x"]);
1
2

Methods

at

at(K key) -> V

The value stored under key.

m.at(k) and m[k] are the same operation.

Parameters

key
The key to look up.

Returns

The value for key.

Throws

RuntimeException
when the map has no entry for key.

Examples

Reading a value

use io::console;

Map<string, int> m = Map();
m["a"] = 1;
console.writeln(m.at("a"));
console.writeln(m.has("zz") ? m.at("zz") : -1);
1
-1

A missing key throws

use io::console;

Map<string, int> m = Map();
m["a"] = 1;
try {
    console.writeln(m.at("zz"));
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
caught: key not found: zz

See also: atOrNone, atOr

atOr

atOr(K key, V dflt) -> V

The value stored under key, or dflt when the key is missing.

The map itself is not changed; the default is not stored.

Parameters

key
The key to look up.
dflt
The value to return when key is not present.

Returns

The stored value, or dflt.

Examples

Counting with a default

use io::console;

Map<string, int> m = Map();
m["a"] = 5;
console.writeln(m.atOr("a", 0));
console.writeln(m.atOr("b", 0));
console.writeln(m.has("b"));
5
0
false

See also: atOrNone

atOrNone

atOrNone(K key) -> V | None

The value stored under key, or None when the key is missing.

Parameters

key
The key to look up.

Returns

The value, or None if there is no entry for key.

Examples

A missing key gives None

use io::console;

Map<string, int> m = Map();
m["a"] = 1;
console.writeln(m.atOrNone("a"));
console.writeln(m.atOrNone("b"));
1
None

See also: at, atOr

clear

mutating clear() -> void

Remove every entry of this map, in place.

Examples

Emptying a map

use io::console;

Map<string, int> m = Map();
m.set("a", 1);
m.clear();
console.writeln(m.length());
0

entries

entries() -> Array<Pair<K, V>>

The entries as an array of Pair<K, V>, in insertion order.

Each pair has the key as first and the value as second.

Returns

A new array with one pair per entry.

Examples

Entries as pairs

use io::console;

Map<string, int> m = Map();
m["a"] = 1;
m["b"] = 2;
for (Pair<string, int> e in m.entries()) {
    console.writeln("${e.first}: ${e.second}");
}
a: 1
b: 2

has

@Pure
has(K key) -> bool

Whether the map has an entry for key.

Parameters

key
The key to test.

Returns

true if key is present.

Examples

Testing for a key

use io::console;

Map<string, int> m = Map();
m["a"] = 0;
console.writeln(m.has("a"));
console.writeln(m.has("b"));
true
false

isEmpty

@Pure
isEmpty() -> bool

Whether the map has no entries.

Returns

true when length() is 0.

Examples

Emptiness

use io::console;

Map<string, int> m = Map();
console.writeln(m.isEmpty());
m["a"] = 1;
console.writeln(m.isEmpty());
true
false

iterator

iterator() -> IIterator<Pair<K, V>>

Return an iterator over the entries as Pair<K, V>, in insertion order.

This is what lets a map be passed where an IIterable<Pair<K, V>> is expected. A for loop over a map does not need it. The iterator walks a snapshot of the map as it was when the iterator was created.

Returns

An iterator positioned before the first entry.

Examples

Walking a map by hand

use io::console;

void walk(Map<string, int> m) {
    IIterator<Pair<string, int>> it = m.iterator();
    while (it.hasNext()) {
        Pair<string, int> e = it.next();
        console.writeln("${e.first}=${e.second}");
    }
}
Map<string, int> m = Map();
m["a"] = 1;
m["b"] = 2;
walk(m);
a=1
b=2

keys

keys() -> Array<K>

The keys, in the order they were first added.

Returns

A new array of the keys.

Examples

Listing keys

use io::console;

Map<string, int> m = Map();
m["b"] = 2;
m["a"] = 1;
console.writeln(m.keys());
[b, a]

See also: values

length

@Pure
length() -> int

The number of entries.

Returns

How many keys the map holds.

Examples

Counting entries

use io::console;

Map<string, int> m = Map();
m["a"] = 1;
m["b"] = 2;
m["a"] = 3;
console.writeln(m.length());
2

mapValues

mapValues<U>((V) => U fn) -> Map<K, U>

Return a new map with the same keys whose values are fn applied to the old values.

The keys keep their order. The value type of the result may differ from V. The receiver is not changed.

Parameters

fn
The transformation applied to each value.

Returns

A new map with transformed values.

Examples

Doubling values

use io::console;

Map<string, int> m = Map();
m["a"] = 1;
m["b"] = 2;
console.writeln(m.mapValues((v) => v * 2));
console.writeln(m.mapValues((v) => "n" + v.toString()));
{a: 2, b: 4}
{a: n1, b: n2}

remove

mutating remove(K key) -> void

Remove the entry for key from this map, in place. A missing key changes nothing.

The verb twin of without, which returns the new map and leaves the receiver alone.

Parameters

key
The key to remove.

Examples

Removing an entry

use io::console;

Map<string, int> m = Map();
m.set("a", 1);
m.set("b", 2);
m.remove("a");
m.remove("zz");
console.writeln(m);
{b: 2}

See also: without

set

mutating set(K key, V val) -> void

Make key map to val in this map, in place.

set is a verb: an imperative name changes the map and returns nothing. It is the named form of the index assignment m[key] = val. Its pure twin is with, which returns the new map and leaves the receiver alone. A key already present keeps its position.

Parameters

key
The key to add or update.
val
The value to store.

Examples

Setting entries

use io::console;

Map<string, int> m = Map();
m.set("x", 1);
m.set("y", 2);
m.set("x", 9);
console.writeln(m);
{x: 9, y: 2}

See also: with

values

values() -> Array<V>

The values, in the same order as keys.

Returns

A new array of the values; element i belongs to key i of keys().

Examples

Listing values

use io::console;

Map<string, int> m = Map();
m["b"] = 2;
m["a"] = 1;
console.writeln(m.values());
[2, 1]

See also: keys

whereEntries

whereEntries((K, V) => bool pred) -> Map<K, V>

Return a new map with only the entries for which pred is true.

The kept entries keep their order. The receiver is not changed.

Parameters

pred
Called with each key and value; the entry is kept when it returns true.

Returns

A new map holding the matching entries.

Examples

Keeping large values

use io::console;

Map<string, int> m = Map();
m["a"] = 1;
m["b"] = 20;
m["c"] = 30;
console.writeln(m.whereEntries((k, v) => v > 10));
console.writeln(m.whereEntries((k, v) => k == "a"));
{b: 20, c: 30}
{a: 1}

with

with(K key, V val) -> Map<K, V>

Return a new map in which key maps to val.

If key is already present its value is replaced and it keeps its position; otherwise the entry is added at the end. The receiver is not changed: with is a prepositional name, so it is pure and returns the new map. Its verb twin set (and the index assignment m[key] = val) changes the map in place.

Parameters

key
The key to add or update.
val
The value to store.

Returns

A new map with the change applied.

Examples

Adding and replacing

use io::console;

Map<string, int> a = Map();
Map<string, int> b = a.with("x", 1).with("y", 2);
Map<string, int> c = b.with("x", 9);
console.writeln(a);
console.writeln(b);
console.writeln(c);
{}
{x: 1, y: 2}
{x: 9, y: 2}

See also: without

withAll

withAll(Map<K, V> o) -> Map<K, V>

Return a new map holding the entries of this map overlaid with the entries of o.

Where both maps have a key, the value from o wins and the key keeps its position from this map. Keys only in o are added after the existing ones. Neither input is changed.

Parameters

o
The map whose entries are added or take precedence.

Returns

The merged map.

Examples

Merging with overrides

use io::console;

Map<string, int> a = Map();
a["x"] = 1;
a["y"] = 2;
Map<string, int> b = Map();
b["y"] = 20;
b["z"] = 30;
console.writeln(a.withAll(b));
console.writeln(a);
{x: 1, y: 20, z: 30}
{x: 1, y: 2}

without

without(K key) -> Map<K, V>

Return a new map without key.

If key is not present the result is equal to the receiver. The receiver is not changed: without is pure; its verb twin remove changes the map in place.

Parameters

key
The key to remove.

Returns

A new map with the entry removed.

Examples

Removing an entry

use io::console;

Map<string, int> m = Map();
m["a"] = 1;
m["b"] = 2;
console.writeln(m.without("a"));
console.writeln(m.without("zz"));
console.writeln(m);
{b: 2}
{a: 1, b: 2}
{a: 1, b: 2}

See also: with

See also

  • Set — A collection of distinct values of type T, with value semantics.
  • Collections are values — Array, Map and Set are values; the in-place verbs (add, set, remove, ...) change the variable you call them on, the prepositional forms (with, without, concat) return a new value.
  • Pair — A pair of two values, possibly of different types.
  • Array — An ordered sequence of values of one type, Array<T>, with value semantics.