Maps in depth

The maps lesson built a map, read a key and changed one. This one goes further: a map inside a map, an update of one nested field, a map that counts, a map used instead of a record, and the conversion between a map and the list of its pairs. The functions are in Erlang's maps module, and every one of them returns a new map.

A nested map

A map value may be a map, so a tree of settings is a map of maps. Reading a nested key is two maps:get/2 calls, or one pattern that names both keys, and the shell prints the whole tree:

erl

1> Config = #{server => #{host => "localhost", port => 8080}}, ok. ok 2> maps:get(port, maps:get(server, Config)). 8080 3> #{server := #{port := Port}} = Config, ok. ok 4> Port. 8080

The second read has no default, so a missing inner key raises badkey rather than returning undefined. A deep pattern such as the third line demands both keys at once, which is the compact form when the whole path is required.

Update one key of a nested map

An update replaces one key of one map. To change a nested field, read the inner map, update it, and put it back; the outer map is a new map as well, and the old tree stays untouched:

erl

1> Config = #{server => #{host => "localhost", port => 8080}}, ok. ok 2> Server = maps:get(server, Config), ok. ok 3> Updated = Config#{server := Server#{port := 9000}}, ok. ok 4> lists:sort(maps:to_list(maps:get(server, Updated))). [{host,"localhost"},{port,9000}] 5> lists:sort(maps:to_list(maps:get(server, Config))). [{host,"localhost"},{port,8080}]

The := on both levels is deliberate: the key must exist, so a typo in port fails at the update instead of adding a second field. When a key may be absent, start from #{} and use =>, as the counter below does.

Count with a map

A map is the natural counter: the key is the thing counted and the value is how often it appeared. maps:get(Key, Map, 0) gives the current count without raising, and the single arrow writes the new one. This module counts letters with a recursive loop:

counter.erl

-module(counter). -export([main/0, bump/2, count/1]). bump(Key, Map) -> Map#{Key => maps:get(Key, Map, 0) + 1}. count(Keys) -> count(Keys, #{}). count([], Acc) -> Acc; count([Key | Rest], Acc) -> count(Rest, bump(Key, Acc)). main() -> io:format("~p~n", [lists:sort(maps:to_list(count([a, b, a, c, a])))]).

erlc counter.erl

erl -noshell -eval 'counter:main(), halt().'

[{a,3},{b,1},{c,1}]

The pairs print in the map's own order, not the order of the input, so a caller that needs a sorted list sorts maps:to_list/1. The standard library has the same update as maps:update_with/3 and maps:update_with/4, which take the function that changes the old value; the funs lesson shows the form.

A map as a record

An atom keyed map with a constructor and getter functions is a record whose fields are a convention instead of a compiler feature. This module keeps a person as a map and reads one field through a function, so the field name appears in one place:

person_map.erl

-module(person_map). -export([main/0, new/2, name/1]). new(Name, Age) -> #{name => Name, age => Age}. name(Person) -> maps:get(name, Person). main() -> Person = new("Ada", 36), io:format("~p~n", [name(Person)]), io:format("~p~n", [maps:size(Person)]).

erlc person_map.erl

erl -noshell -eval 'person_map:main(), halt().'

"Ada" 2

The compiler checks nothing here: name/1 would accept a map without the key and fail at run time. The records lesson shows the form the compiler does check, and Records in depth compares the two for a value that must change shape at run time.

To a list and back

maps:to_list/1 returns the pairs as a list of two-item tuples, and maps:from_list/1 builds a map from such a list. The last value of a repeated key wins. maps:with/2 keeps only the named keys and maps:without/2 removes them:

convert.erl

-module(convert). -export([main/0]). main() -> Map = #{a => 1, b => 2, c => 3}, io:format("~p~n", [lists:sort(maps:to_list(Map))]), io:format("~p~n", [lists:sort(maps:to_list(maps:with([a, c], Map)))]), io:format("~p~n", [lists:sort(maps:to_list(maps:without([b], Map)))]), io:format("~p~n", [lists:sort(maps:to_list(maps:from_list([{x, 1}, {y, 2}])))]).

erlc convert.erl

erl -noshell -eval 'convert:main(), halt().'

[{a,1},{b,2},{c,3}] [{a,1},{c,3}] [{a,1},{c,3}] [{x,1},{y,2}]

maps:to_list/1 and maps:keys/1 return the map's order, so a list that must be sorted is sorted afterwards. The conversions are what a JSON encoder uses: the object becomes a map, the encoder walks maps:to_list/1, and a decoder builds a map with maps:from_list/1.

When a map, when a record

A record is faster and the compiler checks its fields; a map is the only choice when the keys are not known when the module is written, when the set changes while the program runs, or when the value crosses a boundary as JSON or as configuration. The rule of thumb: a fixed shape inside one program is a record, an open shape at the edge of the program is a map.

A map also holds a value whose keys are data, as the counter does, and maps:size/1 answers the number of pairs in constant time. The ETS lesson shows the same key-value idea when the table must be shared by processes and outlive the one that built it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How do you read the port key of the map under server?

    Answer

    maps:get(port, maps:get(server, Config))

    Each level needs its own read or a pattern that names both keys; there is no path syntax.

  2. What does the update of a nested key change?

    Answer

    Nothing: it returns a new outer map with a new inner map

    Both maps are immutable, so the update builds the inner map and then the outer one.

  3. Which call gives a count that may be zero without raising?

    Answer

    maps:get(Key, Map, 0)

    maps:get/3 returns the default for a missing key; the two-argument form raises.

  4. What does maps:to_list/1 return?

    Answer

    A list of {Key, Value} tuples

    The function turns the map into the list of its pairs, in the map's order.

  5. What does maps:from_list([{a, 1}, {a, 2}]) contain?

    Answer

    #{a => 2}

    A repeated key takes the last value in the list.

  6. Which function keeps only the named keys?

    Answer

    maps:with/2

    maps:with/2 returns the pairs whose keys are in the list; maps:without/2 removes them instead.

  7. When is a map the better choice than a record?

    Answer

    When the keys are data or change at run time

    A record needs its fields at compile time; a map takes keys from the running program.

  8. What does this module print? -module(q1). -export([main/0]). main() -> M = #{a => 1}, _ = M#{a := 2}, io:format("~p~n", [M]).

    Answer

    #{a => 1}

    The update returns a new map that nobody keeps, so M still holds 1.

  9. What does this module print? -module(q2). -export([main/0]). main() -> io:format("~p~n", [maps:size(#{a => 1, b => 2, c => 3})]).

    Answer

    3

    The map holds three pairs, so its size is 3.

  10. What does this module print? -module(q3). -export([main/0]). main() -> M = #{a => 1, b => 2, c => 3}, io:format("~p~n", [maps:size(maps:without([b], M))]).

    Answer

    2

    Removing one pair from three leaves two.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev