SoFunction
Updated on 2025-04-08

Detailed introduction to map group map in Erlang

Mainly because I encountered the problem of Map matching, so I recall the mapping group Map in Erlang, which is called Hash hash or Dict dictionary in other languages.

Erlang supports mapping groups starting with R17 version

Create a map group

The mapping group in Erlang is represented by the structure #{}, so it is possible to create a mapping group like this.

Copy the codeThe code is as follows:

% No matter how you sort it, the final result is in dictionary order of the keys
#{ name => "wittyfox", age => 19 }.
% => #{age => 20,name => "wittyfox"}

% You can also create an empty map group
#{}.
% => #{}

Update map group

Mapping groups can be updated, so-called updates are to create a new map group because variables in Erlang are unchangeable.

Copy the codeThe code is as follows:

% Now I
Me = #{ name => "wittyfox", age => 19 }.
% => #{age => 19,name => "wittyfox"}

% It's the New Year, I'm one year older, I've become a brand new me
NewMe = Me#{ age => 20 }.
% => #{age => 20,name => "wittyfox"}

% can also be modified directly
#{ name => "wittyfox", age => 19 }#{ age => 20 }.
% => #{age => 20,name => "wittyfox"}

=> is used to create or update a map, if the key exists, it is updated, otherwise a new map is created. If a key is accidentally spelled by mistake, Oops.

Copy the codeThe code is as follows:

% I originally wanted to update age, but accidentally spelled it wrongly and created a new map
Me#{ aeg => 20 }.
% => #{aeg => 20,age => 19,name => "wittyfox"}.

To avoid this, there is also a way to update the map, using :=, which can only be used to update the map, but cannot create a new map. If the key does not exist, a badarg exception will be thrown.
Copy the codeThe code is as follows:

% Aeg key does not exist, badarg exception is thrown
Me#{ aeg := 20 }.
% ** exception error: bad argument ... blabla

% Only existing maps can be updated
Me#{ age := 20 }.
% => #{age => 20,name => "wittyfox"}

The difference between the two operators

1.=> Can be used to update the map or create a new map
2.:= Only update the map, and an exception will be thrown when the key does not exist.
So there is the following summary

When creating a map group

Only use =>, := can only update the map and cannot create a new map. Several maps are required to create a map group.

Copy the codeThe code is as follows:

#{ name := "wittyfox", age := 19 }.
% * 1: only association operators '=>' are allowed in map construction

Mapping group matching

Only :=, => can be used on the left side to create a new map when the key does not exist, while mapping group matching can be partially matched (only matches the part owned on the left), so matching is meaningless

Copy the codeThe code is as follows:

% Partial match: We just want to remove age, so we only care about whether there is a map of age in the parameters
#{ age := Age } = Me.
% => #{age => 19,name => "wittyfox"}

% Age.
% => 19

% Illegal match
#{ age => Age } = Me.
% * 1: illegal pattern


To find errors better

Use => only when creating a map group or when you explicitly need to create a new map, and in other cases :=

Copy the codeThe code is as follows:

% Here is to create a mapping group, only =>
 new() ->
     {ok, {?MODULE, #{name => "wittyfox", age => 19}}}.

% Here is a match, only :=
 show({?MODULE, #{name := Name, age := Age}}) ->
     io:format("Name: ~p, Age: ~p~n", [Name, Age]).


Notice

The above updates the mapping, creating new mappings and matching can target multiple mappings at the same time, and here is just an example and only one pair of mappings is selected.

Mapping group operation

The maps module in Erlang is used to operate map groups

Mapping group creation and properties

Copy the codeThe code is as follows:

% Create a map group
maps:new().
% => #{}

% Return all keys
maps:keys(Me).
% => [age,name]

% Determine whether there is a key
maps:is_key(age, Me).
% => true
maps:is_key(aeg, Me).
% => false

% key order returns all values
maps:values(Me).
% =>[19,"wittyfox"]

% Map number
maps:size(Me).
% => 2

% You can also use erlang:map_size/1
% This function can be used in Guard, and this function is also used in the maps module.
map_size(Me).
% => 2

Add, delete, and obtain maps

Copy the codeThe code is as follows:

% maps:get/2 Exception will be thrown when the key does not exist
maps:get(age, Me).
% => 19

% maps:get/3 will return the value of the third parameter when the key does not exist.
maps:get(aeg, Me, 20).
% => 20

% is used to update or create a map, similar to =>
% The so-called update is just to return the updated new mapping group, and the original mapping group will not change.
maps:put(gender, male, Me).
% => #{age => 19,gender => male,name => "wittyfox"}

% is used to update the map, similar to :=, badarg exception will be thrown when the key does not exist
maps:update(age, 20, Me).
% => #{age => 20,name => "wittyfox"}

% Delete a map. When the key does not exist, it is equivalent to doing nothing and no exception is thrown.
maps:remove(age, Me).
% => #{name => "wittyfox"}

% Find the value of the key, return error when the key does not exist
maps:find(age, Me).
% => {ok, 19}

maps:find(aeg, Me).
% => error

Merge of map groups

Copy the codeThe code is as follows:

% merges two mapping groups. Note that the second parameter is to create a new mapping group, so you can only use =>
maps:merge(Me, #{ age => 10 }).  
% => #{age => 10,name => "wittyfox"}

% is equivalent to
Me#{ age => 10 }.

Conversion between mapped groups and lists

Copy the codeThe code is as follows:

% Returns a list of mapped tuple pairs
maps:to_list(Me).
% => [{age,19},{name,"wittyfox"}]

%Build a mapping group from a list
maps:from_list([]).
% => #{}

maps:from_list([{name, "wittyfox"}, {age, 19}]).
% => #{age => 19,name => "wittyfox"}

traversal of mapped groups

Copy the codeThe code is as follows:

% Perform an operation on each pair of maps in the map group
%X and Y are the keys and values ​​of a pair of maps, respectively
maps:map(fun (X, Y) -> io:format("~p => ~p~n", [X, Y]) end, Me). 
% age => 19                                                           �
% name => "wittyfox"                                                         �
% => #{age => ok,name => ok}                                                                                                                      �

%X and Y are the keys and values ​​of a pair of maps, V is the result of the last iteration, and 0 is the initial value of the iteration
% is simply used to add 1 to each iteration, and the result is the number of maps of the map group
maps:fold(fun (X, Y, V) -> V + 1 end, 0, Me).
% => 2

Selection of maps in map groups

Returns the mapping group composed of the map of the key specified in the first parameter

Copy the codeThe code is as follows:

maps:with([], Me).
% => #{}

maps:with([age], Me).
% => #{age => 19}

The % key may not exist
maps:with([aeg], Me).
% => #{}


Return the map group composed of maps in the list of the first parameter.
Copy the codeThe code is as follows:

maps:without([], Me).
% => #{age => 19,name => "wittyfox"}

maps:without([age], Me).
% => #{name => "wittyfox"}

The % key may not exist
maps:without([age, neme], Me).
% => #{name => "wittyfox"}


Notice

It is worth mentioning that several functions in the maps module, such as map, fold, with and without, are all used to use maps:to_list/1 to go to the list, then processed using the tools of the lists module, and then use maps:from_list/1 to go back to the mapping group.