jonnifyelixir
F4 / F4.04 / lookup

F4.04 · part 1 of 3

Maps & key lookup

A map associates keys with values and retrieves a value by its key in effectively constant time, no matter how many entries it holds. The course’s page registry is exactly this: a map from a route string to a %Page{} struct. Map.get returns the value or nil, Map.fetch returns a tagged result, and Map.put returns a new map with the entry added or replaced.

Looking up the page for "/elixir/algorithms/maps" — this very page — in the registry, and adding a new one. Select an operation.

Three ways to touch a map

Map.get and Map.fetch read by key — the difference is only how they report a miss. Map.put writes, returning a fresh map and leaving the original untouched, because maps are immutable. Select one.

The operation · select one

QUERY KEY "/elixir/algorithms/maps" → pages (keys) "/elixir/algorithms/maps" "/elixir/algorithms/sorting" "/elixir/language/modules" "/elixir/language/under-the-hood" → RESULT %Page{}

      

role: value, or nil if absent

result: %Page{title: "Maps, sets & hashing"}

Reads and writes are both keyed: you never scan. get and fetch differ only in how a miss comes back — nil versus :error — and put returns a new map, never mutating the old one.

Advanced: updates, structs & assigns

There are two ways to change a value. The update syntax %{map | key => value} is strict — it raises if the key is missing — while Map.put/3 always succeeds, adding the key if needed. A %Page{} struct is itself a map with a hidden :__struct__ key, so the same functions work on it, with compile-time checking of field names. And the structure you meet constantly in Phoenix is a map: a LiveView’s socket.assigns holds the page in a map, and assign/3 returns a new socket with an updated copy — the immutable Map.put in disguise.

# strict update (key must exist) vs Map.put (adds if missing)
%{page | built: true}          # raises if :built is not already a key
Map.put(page, :built, true)    # always returns a new struct

# a struct is a map with a __struct__ key
page.__struct__                  # => Jonnify.Course.Page

# in a LiveView, assigns is a map; assign/3 returns a new socket
def mount(%{"route" => route}, _session, socket) do
  {:ok, assign(socket, :page, Jonnify.Course.fetch!(route))}
end

F4.01 · a list lookup is O(n)

Finding an element in a list means walking it.

F4.04.1 · a map lookup is O(1)

Fetch a page by its exact route in constant time, however large the registry grows.

Next: MapSet & membership — the same keyed lookup, asked as a yes/no question over the course’s route sets.

References

Primary sources for this lesson, and where it connects in the course.