Maps
A map is the key store of Elixir: a set of keys, each with one value, where the keys are looked up in one step whatever the size. It is the data shape a function returns when the fields have names, and the shape a JSON document becomes when it is parsed. Read the map lesson together with keyword lists, which are the other way to carry named values and the one a function takes as its options.
The map literal
Percent braces hold the pairs. An atom key is written in the short form, name: value, and any other key uses the arrow, "name" => value. The two forms can share one map, and map_size/1 counts the entries:
literal.exs
user = %{name: "Ada", age: 36} mixed = %{"role" => :admin, name: "Ada"} IO.inspect(user) IO.inspect(mixed) IO.puts(map_size(user)) IO.puts(map_size(mixed))
elixir literal.exs
%{name: "Ada", age: 36}
%{:name => "Ada", "role" => :admin}
2
2
The mixed map is printed with the arrow on both keys, because the short form is only a shorthand for a map whose keys are all atoms. The order of the pairs in the output is not a promise either: a map with more than a few dozen keys is shown sorted, and code that depends on the printed order has a bug that appears when the map grows. map_size/1 is the count, read from the map header, and Map.keys/1 gives the keys when the program needs them as a list.
Dot and brackets
The dot reads an atom key and raises when the key is not there. The brackets take any key and answer nil for a missing one, and Map.get/3 does the same with a default instead of nil:
read.exs
user = %{name: "Ada", age: 36} IO.puts(user.name) IO.puts(user[:age]) IO.inspect(user[:missing]) IO.inspect(Map.get(user, :missing, "unknown"))
elixir read.exs
Ada
36
nil
"unknown"
The dot is the right form when the key is part of the shape the code expects, because a missing key is then a bug that should stop the program. The brackets and Map.get/3 are for the keys that may be absent, such as an optional field of a request.
Updating an entry
The update form repeats the map on the left and names the new values on the right. It changes the keys that already exist and raises when one is absent, which catches a misspelled key at once. Map.put/3 adds a key that may be new, and Map.delete/2 removes one:
update.exs
user = %{name: "Ada", age: 36} older = %{user | age: 37} IO.inspect(older) with_city = Map.put(user, :city, "London") IO.inspect(with_city) IO.inspect(Map.delete(with_city, :age))
elixir update.exs
%{name: "Ada", age: 37}
%{name: "Ada", age: 36, city: "London"}
%{name: "Ada", city: "London"}
Every update returns a new map; the old one is untouched, so a program can keep both versions. The compiler cannot see inside a map the way it sees inside a tuple, so the check of the update form happens at run time, and the error is a KeyError that names the key.
Keys of any type
A map takes any value as a key, and a string key is a common case when the data comes from a file or from JSON. The bracket is then the only way in, because the dot form is only for atom keys. The functions of the map module work the same for every key type:
mixed.exs
counts = %{"apples" => 3, "pears" => 5} IO.inspect(counts["apples"]) IO.inspect(Map.put(counts, "plums", 2)) IO.inspect(Map.keys(counts) |> Enum.sort())
elixir mixed.exs
3
%{"apples" => 3, "pears" => 5, "plums" => 2}
["apples", "pears"]
Matching works for keys too: %{name: name} = user binds the value when the key is present, and a pattern with a key the map does not have does not match. A pattern that names one key matches a map with ten, which is how a function takes the field it needs and ignores the rest.
The mistake: a dot on a missing key
The dot form promises that the key is there. When it is not, the lookup raises a KeyError and prints the whole map, which is exactly what a reader needs to see the typo:
mistake.exs
user = %{name: "Ada"} IO.puts(user.age)
elixir mistake.exs
** (KeyError) key :age not found in:
%{name: "Ada"}
mistake.exs:3: (file)
(elixir 1.19.7) lib/code.ex:1613: Code.require_file/2
The fix is the bracket form when the key is optional, and a pattern or a guard when the program has to decide: Map.get(user, :age) answers nil and lets the next line choose, while the dot keeps the failure close to the line that caused it. A map field read with a dot and written with a string key is the same mistake in another disguise: the atom :name and the binary "name" are two different keys.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which read of a map raises when the key is missing?
Answer
map.key
The dot promises an atom key that is there; the bracket and Map.get answer nil instead.
-
What does the update form
%{map | key: value}do with a key that is not in the map?Answer
It raises a KeyError
The update form changes existing keys only, and a missing key is a run-time error.
-
What is the difference between the keys
:nameand"name"in one map?Answer
They are two different keys
A map compares keys by value, and an atom is not the same value as a binary.
-
What does this program print?
user = %{name: "Ada"} IO.inspect(user[:age])Answer
nil
The bracket form answers nil for a key the map does not hold.
-
What does this program print?
user = %{name: "Ada", age: 36} IO.inspect(%{user | age: 37})Answer
%{name: "Ada", age: 37}
The update form changes the value of the existing age key and keeps the rest.
-
What does this program print?
IO.inspect(Map.get(%{a: 1}, :b, 0))Answer
0
Map.get/3 returns its third argument when the key is absent.
-
What does this program print?
IO.puts(map_size(%{a: 1, b: 2}))Answer
2
map_size/1 counts the entries of the map.
-
What does this program print?
%{name: name} = %{name: "Ada", age: 36} IO.puts(name)Answer
Ada
A map pattern matches when its keys are present, and the extra keys are ignored.
-
What does this program print?
IO.inspect(%{a: 1} |> Map.put(:b, 2) |> Map.get(:b))Answer
2
Map.put/3 adds the key and the next step reads the value it added.
-
What does this program do?
user = %{name: "Ada"} IO.puts(user.age)Answer
A KeyError, because the map has no age key
The dot form raises a KeyError when the atom key is not in the map.
Автор статьи: Arthur Isaev