Skip to content

Maps

Map<K, V> is a dictionary with keys of type K and values of type V. Use %{key => value} for a map literal or gale_std.map.from_list to build one from key-value tuples. %{} is an empty map; {} is the empty tuple.

Map<K, V> stores values of type V under keys of type K. Keys can come from runtime data, making maps useful for counts, caches and indexes.

Build a map from pairs, then look up a key:

mod maps
alias gale_std.map
pub fn scores() -> Map<String, Integer> {
map.from_list([{"ada", 36}, {"al", 41}])
}
pub fn score(scores: Map<String, Integer>, name: String) -> Option<Integer> {
map.get(scores, name)
}

map.get returns Option<V>: a missing key is None, while a stored nil is Some(nil). from_list keeps the last value for duplicate keys. Use an explicit merge when repeated keys should accumulate values instead of replacing them.

Updates return a new dictionary; existing bindings keep the old one. The %{key => value} syntax builds a single-entry map with a runtime key:

mod maps
alias gale_std.map
@doc "Runtime keys use =>; updates return a new map."
pub fn increment(counts: Map<String, Integer>, key: String) -> Map<String, Integer> {
count = case map.get(counts, key) {
Some(value) -> value
None -> 0
}
map.put(counts, key, count + 1)
}
pub fn singleton(key: String, value: Integer) -> Map<String, Integer> {
%{key => value}
}

Map keys distinguish 1 from 1.0 and the two signed zeros, just like list membership. A Map<String, Integer> can be used where Map<String, Term> is expected, but not where Map<Term, Integer> is expected: values may widen, while the key type must stay the same.

Iteration order is unspecified. Use map.to_list when you need key-value pairs; separately enumerating map.keys and map.values does not promise matching positions. map.values preserves every value’s occurrence count, regardless of order.

When merging maps, the right-hand map wins for duplicate keys. map.get(data, key, default) evaluates the default eagerly, even when the key exists. Use a case on map.get(data, key) to compute a fallback only when needed.

A Map type does not specify which keys exist. Use a record when the fields are fixed.