Maps

A map is a set of keys and values with no fixed shape: keys may be added and removed, the map grows and shrinks, and any term can be a key. It is the structure of Erlang for settings, a JSON object, or a record whose fields are known only at run time.

Build a map

The hash and braces build a map, and each pair is a key, an arrow and a value. The empty map is the hash alone. The shell prints the pairs in its own order, not necessarily the order they were typed:

erl

1> #{name => "Ada", age => 36}. #{name => "Ada",age => 36} 2> #{}. #{} 3> #{1 => one, {a, b} => tuple_key, <<"k">> => binary_key}. #{1 => one,{a,b} => tuple_key,<<"k">> => binary_key}

Keys are ordinary terms, so two maps with the same pairs are the same value whatever order the pairs were written in. The => of a literal is not the same symbol as := of an update, which the next sections use.

Read a key

maps:get/2 returns the value and raises when the key is absent; maps:get/3 takes a default and never raises. maps:find/2 answers {ok, Value} or the atom error, which a case can match. There is no dot access to a map: the dot belongs to records.

erl

1> M = #{name => "Ada"}. #{name => "Ada"} 2> maps:get(name, M). "Ada" 3> maps:get(age, M, 0). 0 4> maps:find(age, M). error 5> maps:keys(M). [name] 6> maps:values(M). ["Ada"]

maps:keys/1 and maps:values/1 return lists, not sets, and their order is the map's, so sort them when the order matters. The call maps:get(age, M) without a default raises {badkey, age}, which is the failure to expect when a key is required.

Update a key

In an update expression, => adds or replaces a key and := updates a key that must already exist. Both return a new map and leave the old one untouched, as every value in the language does:

erl

1> M = #{name => "Ada"}. #{name => "Ada"} 2> M#{age => 36}. #{name => "Ada",age => 36} 3> M#{name := "Grace"}. #{name => "Grace"} 4> M. #{name => "Ada"}

The double arrow on a missing key raises badkey; the single arrow adds it. Use => when the key may be new and := when its presence is part of the logic, as in an update of a field that a caller promised to pass.

Keys and matching

A map pattern names the keys it needs and binds their values. The pattern matches any map that holds those keys, with any number of other keys, and only := is allowed there: the compiler rejects => in a pattern, because a pattern must never invent a key:

erl

1> #{name := Who} = #{name => "Ada", age => 36}. #{name => "Ada",age => 36} 2> Who. "Ada" 3> #{name => Who} = #{name => "Ada"}. * 1:8: illegal pattern, did you mean to use `:=`?

The error is one line and points at the arrow, which makes the fix easy. The same rule is what lets a function clause accept a map with at least the keys it needs and ignore the rest.

A map used as a setting

A map of settings shows all three operations at once: defaults, a merge with the caller's values, and a read with a default. This module keeps a host and a port and prints the merged map and the port it would use:

config.erl

-module(config). -export([main/0, port/1]). defaults() -> #{host => "localhost", port => 8080}. port(Settings) -> maps:get(port, Settings, 8080). main() -> Custom = #{port => 9000}, Merged = maps:merge(defaults(), Custom), io:format("~p~n", [Merged]), io:format("~p~n", [port(Merged)]), io:format("~p~n", [port(#{})]).

erlc config.erl

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

#{port => 9000,host => "localhost"} 9000 8080

maps:merge/2 gives the second map the last word, so the custom port wins and the default host remains. The last line reads a map without the key and gets the default, which is the difference between maps:get/3 and maps:get/2.

An update with := and a pattern both work on one field of a nested value. This module renames a user and reads the name back with a pattern:

user.erl

-module(user). -export([main/0, rename/2]). rename(User, Name) -> User#{name := Name}. main() -> User = #{name => "Ada", age => 36}, Older = User#{age => 37}, io:format("~p~n", [rename(Older, "Grace")]), #{name := Name} = User, io:format("~s~n", [Name]).

erlc user.erl

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

#{name => "Grace",age => 37} Ada

Older is a new map and User is unchanged; the pattern at the end reads the original. The Maps in depth lesson covers the module's match specifications, nested updates and the choice between a map and a record.

Questions

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

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

    Answer

    3

    maps:merge/2 lets the second map win, so b holds 3.

  2. Which value is the empty map?

    Answer

    #{}

    The hash with no pairs is the empty map, distinct from the empty tuple and the empty list.

  3. What does maps:find(age, #{name => "Ada"}) return when age is absent?

    Answer

    The atom error

    maps:find/2 answers {ok, Value} or the atom error; only maps:get/2 raises.

  4. What does the single arrow => do in a map expression?

    Answer

    Adds or replaces a key

    => builds a pair, whether the key is new or already present.

  5. What does the double arrow := do in a map expression?

    Answer

    Updates a key that must already exist

    := updates an existing key and raises a badkey error when the key is absent.

  6. Why does the compiler reject #{name => Who} = M?

    Answer

    The pattern may invent a key, so := is required

    In a pattern the double arrow demands a key that exists; => would add one, which a match cannot do.

  7. Does an update change the original map?

    Answer

    No, it returns a new map and the original is untouched

    Every term is immutable, so an update builds a new map.

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

    Answer

    #{port => 9000}

    The key exists, so := replaces its value and the new map prints with 9000.

  9. What does this module print? -module(q2). -export([main/0]). main() -> M = #{name => "Ada", age => 36}, #{name := Name} = M, io:format("~s~n", [Name]).

    Answer

    Ada

    The pattern binds the value of name and ~s prints the string without quotes.

  10. What does this module print? -module(q3). -export([main/0]). main() -> M = #{name => "Ada"}, io:format("~p~n", [maps:get(age, M, 0)]).

    Answer

    0

    maps:get/3 returns the default when the key is absent, so the call never fails.

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.

Article author: Arthur Isaev