Nested data
Real data is rarely one flat map. A response from an API is a map whose values are lists of maps, a configuration file is a map several levels deep, and an order is a customer inside an address inside a list of items. Elixir has two ways to work with that shape: the dot and the bracket for a known path, and get_in, put_in and update_in for a path the program builds.
A map inside a map
The literal of a nested map is a map whose value is another map, and a list of maps is the usual way to hold rows. The shape is the data model: the keys at each level say what that level is, and a reader sees the levels from the indentation:
get.exs
order = %{ id: 1, customer: %{name: "Ada", address: %{city: "London", postcode: "N1"}} } IO.inspect(order.customer.name) IO.inspect(order.customer.address.city) IO.inspect(get_in(order, [:customer, :address, :city])) IO.inspect(get_in(order, [:customer, :missing, :city])) IO.inspect(order[:customer][:address][:postcode])
elixir get.exs
"Ada"
"London"
"London"
nil
"N1"
The dot form and get_in/2 read the same value; the difference is what happens when a level is missing. The dot raises a KeyError, the bracket chain raises when an intermediate value is nil, and get_in/2 answers nil for the whole path. A program that treats a missing level as absent data uses get_in/2; a program that requires the level uses the dot and lets the crash name the missing key.
put_in and update_in
put_in/3 writes a value at a path and returns a new structure with every level copied on the way, and update_in/3 applies a function to the value it finds. The path is a list of keys, or the dotted form of the value itself, which is the macro spelling of the same call:
put.exs
order = %{ id: 1, customer: %{name: "Ada", address: %{city: "London", postcode: "N1"}} } IO.inspect(put_in(order, [:customer, :address, :city], "Paris")) IO.inspect(update_in(order, [:customer, :name], &String.upcase/1)) IO.inspect(put_in(order.customer.address.city, "Rome"))
elixir put.exs
%{id: 1, customer: %{name: "Ada", address: %{city: "Paris", postcode: "N1"}}}
%{id: 1, customer: %{name: "ADA", address: %{city: "London", postcode: "N1"}}}
%{id: 1, customer: %{name: "Ada", address: %{city: "Rome", postcode: "N1"}}}
The three calls print three different maps, and the original is untouched by all of them. A nested update copies the maps along the path and shares the branches that did not change, which is why the cost of a deep update grows with the depth rather than with the size of the data. Nested access goes further with a struct inside a struct.
Lists inside the map
A list is part of the path, and Access.at/1 names one position of it. Reading a field of every row is a map over the list, and the totals are an Enum call away:
lists.exs
order = %{ id: 1, items: [%{sku: "A1", qty: 2}, %{sku: "B2", qty: 1}] } IO.inspect(get_in(order, [:items, Access.at(0), :sku])) IO.inspect(put_in(order, [:items, Access.at(0), :qty], 5)) total = order.items |> Enum.map(& &1.qty) |> Enum.sum() IO.puts(total)
elixir lists.exs
"A1"
%{id: 1, items: [%{sku: "A1", qty: 5}, %{sku: "B2", qty: 1}]}
3
Access.at/1 is one of the access functions, and it is the one a path uses for a list index. The update returns a new list with a new map at position 0; the row that did not change is the same value in both lists.
A shape that stays readable
Depth is the cost of nested data, and the code pays it twice: once in the path that reads a value, once in the reader who has to count the levels. Three habits keep the shape readable:
- give each level a name that says what it is, and keep the levels shallow: a customer inside an order, not a customer inside an order inside a session inside a request;
- match at the boundary once, %{customer: %{address: %{city: city}}} = order, and pass the small value on rather than the whole structure;
- use a struct for the parts the program owns, and a map for the parts that arrive from outside, because a struct refuses a key it does not know while a map accepts any.
The mistake: a path through a key that is not there
put_in/3 writes through the path it is given. When a level in the middle is absent there is nothing to write into, and the call raises an ArgumentError that names the key it could not reach:
mistake.exs
order = %{id: 1, customer: %{name: "Ada"}} IO.inspect(put_in(order, [:customer, :address, :city], "Paris"))
elixir mistake.exs
** (ArgumentError) could not put/update key :city on a nil value
(elixir 1.19.7) lib/access.ex:436: Access.get_and_update/3
(elixir 1.19.7) lib/map.ex:965: Map.get_and_update/3
(elixir 1.19.7) lib/kernel.ex:2950: Kernel.put_in/3
mistake.exs:3: (file)
The message names the last key of the path and the value it found, which is nil because :address was missing. The fix is to write each level the program creates, put_in(order, [:customer, :address], %{city: "Paris"}), or to build the missing map on the way with Map.put_new/3. A read with get_in/2 would have answered nil, which is why the two directions have to agree on whether the path is required.
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.
-
What does
get_in/2answer when a level of the path is missing?Answer
nil
get_in treats a missing level as absent data and answers nil for the whole path.
-
What does
put_in/3do to the structure it is given?Answer
Returns a new structure with the maps along the path copied
The call returns a new value, and the maps that did not change are shared with the old one.
-
Which call applies a function to a value at a path?
Answer
update_in/3
update_in/3 carries the old value into the function and writes back what it returns.
-
What does
Access.at/1name in a path?Answer
a position of a list
A list has positions rather than keys, and Access.at/1 gives a path one.
-
What does this program print?
order = %{customer: %{name: "Ada"}} IO.inspect(get_in(order, [:customer, :name]))Answer
"Ada"
get_in reads the path and prints the binary value with its quotes.
-
What does this program print?
order = %{customer: %{name: "Ada"}} IO.inspect(get_in(order, [:customer, :age]))Answer
nil
The last key is missing, and get_in answers nil rather than raising.
-
What does this program print?
order = %{customer: %{city: "London"}} IO.inspect(update_in(order, [:customer, :city], &String.upcase/1))Answer
%{customer: %{city: "LONDON"}}
The function is applied to the value and the new value is written at the same path.
-
What does this program print?
order = %{items: [%{qty: 2}, %{qty: 1}]} IO.puts(order.items |> Enum.map(& &1.qty) |> Enum.sum())Answer
3
The map takes the quantity of each row and the sum adds them.
-
What does this program do?
order = %{customer: %{name: "Ada"}} IO.inspect(put_in(order, [:customer, :address, :city], "Paris"))Answer
An ArgumentError, because :address is nil on the path
put_in cannot write through a level that is not there, and the error names the last key.
-
Which value does the dot read raise on when a level is missing?
Answer
a KeyError
The dot promises the key is there, and a missing one raises a KeyError.
Автор статьи: Arthur Isaev