SortedMap
import "std/collections" (included in import "std") · namespace std.collections
SortedMap<K, V> keeps its keys sorted by a comparison function you give it. Lookups are O(log n) (binary search); inserting and removing are O(n). It answers questions a plain map cannot: the smallest key, the largest, or every key in a range.
grav
import "std"
fn main() {
let scores = new SortedMap<string, int>(fn(a, b) => Str.compare(a, b))
scores["carol"] = 88
scores["alice"] = 95
scores["bob"] = 72
print(scores.keys())
print("${scores.firstKey()} ${scores.lastKey()}")
print(scores.keysBetween("b", "c"))
scores.forEach(fn(name, s) { print("${name}: ${s}") })
let byTime = new SortedMap<int, string>(fn(a, b) => a - b)
byTime[930] = "standup"
byTime[800] = "coffee"
byTime[1200] = "lunch"
print(byTime.values())
}["alice", "bob", "carol"]
alice carol
["bob"]
alice: 95
bob: 72
carol: 88
["coffee", "standup", "lunch"]get with a missing key throws NotFound; firstKey and lastKey on an empty map throw IndexError.
API
class SortedMap<K, V> implements Iterable<Entry<K, V>>
Constructors
new SortedMap(cmp: fn(K, K) -> int)
Methods
fn put(key: K, value: V)— Sets the value forkey(adding it in order, or replacing its value).fn get(key: K) -> V— The value forkey(NotFound when missing).fn getOr(key: K, fallback: V) -> V— The value forkey, orfallbackwhen missing.fn operator[](key: K) -> V—m[key]: the value for key (NotFound when missing).fn operator[]=(key: K, value: V)—m[key] = value: sets the value for key.fn containsKey(key: K) -> bool— Whether the map haskey.fn remove(key: K) -> bool— Removeskey; whether it was there.fn size() -> int— The number of keys.fn length() -> int— The number of keys (same as size()).fn isEmpty() -> bool— Whether the map is empty.fn clear()— Removes every key.fn firstKey() -> K— The smallest key (IndexError when empty).fn lastKey() -> K— The largest key (IndexError when empty).fn toString() -> string— Keys and values in key order (copies). As text: {"a": 1, "b": 2} (strings in quotes).fn keys() -> Array<K>— The keys in order (a copy).fn values() -> Array<V>— The values in key order (a copy).fn keysBetween(lo: K, hi: K) -> Array<K>— Keys k with lo <= k < hi, in order.fn forEach(f: fn(K, V))— Calls f with each key and value, in key order.fn iterator() -> EntryIterator<K, V>— Every key with its value, one at a time, in key order: whatfor ((k, v) in map)uses.fn entries() -> Array<Pair<K, V>>— Every key with its value, as pairs, in key order.