Home / Docs / Standard library / Built-in methods
set
A built-in method, resolved by the type of its receiver (spec/14 §2). Edition 0.2 and later.
Edition 0.2 and later
edit m.set(key: K, value: V) -> Unit
where m: Map[K, V]Updates m in place, written edit m.set(...): afterwards m.has(key: k) and m.get(key: k) == Some(v), and m.len grows by one when the key was not there (spec/21 §2). On a HashMap, a key already there keeps its place in the listing, in O(|k|) expected, amortized (spec/28 §7).
Edition 0.5 preview
edit m.set(key: K, value: V) -> Unit
where m: Map[K, V]
edit m.set(key: K, value: V) -> Unit
where m: HashMap[K, V]Updates m in place, written edit m.set(...): afterwards m.has(key: k) and m.get(key: k) == Some(v), and m.len grows by one when the key was not there (spec/21 §2). On a HashMap, a key already there keeps its place in the listing, in O(|k|) expected, amortized (spec/28 §7).
In editions 0.5. In edition 0.2, 0.3, 0.4: no HashMap[K, V] receiver, since std.collections begins in edition 0.5: it has no where m: HashMap[K, V].
Receiver
Map[K, V]: the mapm, changed in place, writtenedit m.set(...)HashMap[K, V]: the hash mapm, changed in place, writtenedit m.set(...); a key already there keeps its place in the listing
Parameters
key: the key; from edition 0.3, with a refined key typeK, it is stored atK, an obligation thatuna checkproves at the callvalue: the new value atkey; from edition 0.3, with a refined value typeV, it is stored atV, an obligation thatuna checkproves at the call
Returns
Unit: nothing; afterwards m.get(key: key) == Some(value), and m.len grows by one when key was not there.
Use instead
withfor a new map, leaving the old one as it is
See also
Cost
Time O(log n) per lookup, insertion and removal on a Map[K, V] (spec/21 §5), where:
n: the number of entries inm; in the native runtime the update is in place whenmis uniquely held, and on a copy, in O(n), otherwise
Example
module shop
--- A recount replaces the stock of an item.
pub main() -> Unit
uses @console: Console[print]
=
let edit stock = empty_map().with(key: "lamp", value: 3)
edit stock.set(key: "lamp", value: 5)
let units = stock.get(key: "lamp").or_else(default: 0)
@console.print("lamp: {units}, entries: {stock.len}")una run . prints:
lamp: 5, entries: 1Specification
- spec/21 §2
spec/28 §7
Generated from una v0.4.0 (docs/std/builtins.json, which is not part of the specification): built-in methods have no declaration, so una writes these signature lines and tests each against its checker. The specification governs: spec/14 §2.