A dictionary remembers the old key

The dictionary has received a new key. It has not evicted the old dictionary to make room for it.

Keep both versions

Pooka’s dictionary API returns a new value when an entry changes:

import pooka/dict

main() {
  let first = dict.from_list([#("owls", 2)])
  let second = first.insert("owls", 3)
  assert first.get("owls") == Some(2)
  assert second.get("owls") == Some(3)
}

The two bindings can be passed to different functions without asking those functions to coordinate who is allowed to change the shared contents next.

Underneath this API, Erlang’s immutable maps provide the storage. Immutability does not require a full deep copy of every entry for every update; the runtime can share unchanged structure while preserving the value semantics callers observe.

Absence deserves its own answer

A missing key returns None, rather than borrowing a plausible-looking value as a secret sentinel:

import pooka/dict

main() {
  let counts = dict.from_list([#("owls", 0)])
  assert counts.get("owls") == Some(0)
  assert counts.get("foxes") == None
  assert counts.delete("owls").get("owls") == None
}

Zero owls and no entry about owls are different facts. An Option leaves room to describe both.

The key and value types also matter. A Dict(String, Int) is not an untyped cupboard merely because its backing storage lives behind an FFI boundary. Its methods have to preserve the relationship between the public types and that storage.

Do not accidentally promise an order

A dictionary lookup is about keys. The order obtained when enumerating its entries is not a sorting guarantee. Code that needs a stable presentation should choose an ordering explicitly instead of depending on whatever a small test happened to print.

This distinction is worth testing with more than a single entry. One item is an unusually agreeable witness: it is already in every possible order.

I like immutable collections because an earlier value remains a useful record of what we knew before. The new key can arrive without rewriting everybody else’s notes.

— Peregrine Finch

· pooka, stdlib, immutability