Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Data Structures

Maps

Use Erlang maps as key-value data: create, read, update with => and :=, pattern match, iterate, use the maps module and choose between maps, records and proplists.

A map associates keys with values. It is the right structure for dictionaries, JSON-like data, configuration and any record whose fields are not known in advance. Maps were introduced in OTP 17 and are now the standard key-value type, replacing most uses of property lists and the old dict module.

Creating and reading

ERLANG
1> M = #{name => "Ada", age => 36}.
#{age => 36,name => "Ada"}
2> maps:get(name, M).
"Ada"
3> maps:get(city, M, "unknown").
"unknown"
4> maps:find(age, M).
{ok,36}
5> maps:find(city, M).
error
6> map_size(M).
2
7> #{}.
#{}

Keys can be any term: atoms, strings, numbers, tuples. Atom keys are most common. maps:get/2 raises a badkey error if the key is missing; maps:get/3 gives a default; maps:find/2 returns {ok, V} or error; and maps:is_key/2 checks existence. Printing shows the keys in sorted order for small maps, but you should never rely on key order.

In guards you can read a value with the built-in map_get(Key, Map).

Updating: => versus :=

Maps are immutable, so "updating" produces a new map:

ERLANG
1> M = #{name => "Ada", age => 36}.
2> M#{age := 37}.
#{age => 37,name => "Ada"}
3> M#{city => "London"}.
#{age => 36,city => "London",name => "Ada"}
4> M#{city := "London"}.
** exception error: {badkey,city}
5> M#{age => 37, name => "Grace"}.
#{age => 37,name => "Grace"}
  • Map#{Key => Value} adds or replaces the key.
  • Map#{Key := Value} updates only an existing key and fails with badkey if it is missing. Use it to catch typos.
  • You can change several keys at once.

The original M is unchanged after every update.

Pattern matching on maps

Use := in patterns. A pattern matches if the map contains at least those keys with matching values:

ERLANG
-module(greet).
-export([hello/1]).

hello(#{name := Name, title := Title}) ->
    io:format("Hello, ~s ~s!~n", [Title, Name]);
hello(#{name := Name}) ->
    io:format("Hello, ~s!~n", [Name]);
hello(_) ->
    io:format("Hello, stranger!~n").
ERLANG
1> greet:hello(#{name => "Ada", title => "Dr."}).
Hello, Dr. Ada!
2> greet:hello(#{name => "Ada", age => 36}).
Hello, Ada!
3> greet:hello(#{}).
Hello, stranger!

The first clause demands both keys; the second matches any map with a name, ignoring the rest. Key expressions in a pattern must be bound variables or literals, not unbound variables, so you cannot match on an unknown key.

Maps can be used in guards too:

ERLANG
adult(#{age := Age}) when Age >= 18 -> true;
adult(_) -> false.

The maps module

Function What it does
maps:keys/1, maps:values/1 Lists of keys / values
maps:to_list/1, maps:from_list/1 Convert to/from [{K, V}]
maps:put/3, maps:update/3 Like => and :=
maps:remove/2 Delete a key
maps:merge/2 Combine two maps (right side wins)
maps:map/2 Transform every value: fun(K, V) -> NewV end
maps:filter/2 Keep pairs for which the fun returns true
maps:fold/3 Fold over pairs: fun(K, V, Acc) -> NewAcc end
maps:with/2, maps:without/2 Keep or drop a list of keys
maps:update_with/3 Update a value with a fun
ERLANG
1> M = #{a => 1, b => 2, c => 3}.
2> maps:map(fun(_K, V) -> V * 10 end, M).
#{a => 10,b => 20,c => 30}
3> maps:filter(fun(_K, V) -> V > 1 end, M).
#{b => 2,c => 3}
4> maps:fold(fun(_K, V, Acc) -> V + Acc end, 0, M).
6
5> maps:merge(#{a => 1}, #{a => 2, b => 3}).
#{a => 2,b => 3}
6> maps:from_list([{x, 1}, {y, 2}]).
#{x => 1,y => 2}
7> maps:update_with(a, fun(V) -> V + 100 end, M).
#{a => 101,b => 2,c => 3}
8> maps:remove(a, M).
#{b => 2,c => 3}

Counting words is a classic use:

ERLANG
count(Words) ->
    lists:foldl(
        fun(W, Acc) -> maps:update_with(W, fun(N) -> N + 1 end, 1, Acc) end,
        #{},
        Words).

maps:update_with/4 takes a default for a missing key, so the first sight of a word sets its count to 1.

Iteration

Since OTP 26 map generators work in comprehensions, and you can also iterate with maps:iterator/1 and maps:next/1. The common style:

ERLANG
[{K, V * 2} || {K, V} <- maps:to_list(M)]

Performance

Small maps (up to 32 keys) are stored as sorted arrays and are very quick. Larger ones switch to a hash array mapped trie with logarithmic access. Maps are a good default, but for very large mutable tables shared by many processes, the ETS tables covered in later chapters are the tool.

Maps, records or proplists?

Use a map when keys are dynamic, when data comes from JSON or configuration, or when you want to add fields without touching every pattern. Use a record for fixed internal structures and speed. Property lists like [{debug, true}] still appear in old APIs; convert with maps:from_list/1.

Stand-ins in JavaScript

JavaScript's Map and object spread behave similarly. These samples are not Erlang.

JS Stand-in: add versus update on an immutable map (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: word count with update_with (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between M#{k => v} and M#{k := v}?

    := raises badkey if the key is missing, which catches mistakes.
  2. 2. Which operator do you use for a key in a map pattern?

    Patterns use := , for example #{name := N} = Map.
  3. 3. What does maps:get(city, M, "unknown") do when city is missing?

    The third argument is a default value.
  4. 4. What happens to the original map after M#{age := 37}?

    Maps are immutable. Every update builds a new map.

Summary

  • Maps hold key-value pairs: #{key => value}; keys can be any term.
  • => adds or replaces; := updates only existing keys and raises badkey otherwise.
  • Patterns use := and match maps that contain at least the listed keys.
  • The maps module offers get, find, put, remove, merge, map, filter, fold, keys, values and more.
  • Choose maps for dynamic data, records for fixed structures.

Next: Binaries and Bit Syntax