Maps in Erlang
Based on your input, here is the translation to Erlang along with explanations:
Maps are Erlang’s built-in associative data type (sometimes called hashes or dicts in other languages).
To create an empty map, use the following syntax:
m = #{}
Set key/value pairs using typical map syntax.
m = maps:put("k1", 7, m),
m = maps:put("k2", 13, m)
Printing a map with io:format
will show all of its key/value pairs.
io:format("Map: ~p~n", [m])
Get a value for a key with maps:get(Key, Map)
.
V1 = maps:get("k1", m),
io:format("V1: ~p~n", [V1])
If the key doesn’t exist, the function may throw an error, so it’s advised to use maps:find/2
which returns {ok, Value}
or error
.
case maps:find("k3", m) of
{ok, V3} -> io:format("V3: ~p~n", [V3]);
error -> io:format("V3: zero_value~n")
end.
The maps:size
returns the number of key/value pairs in the map.
io:format("Size: ~p~n", [maps:size(m)])
To remove key/value pairs from a map, use maps:remove/2
.
m = maps:remove("k2", m),
io:format("Map: ~p~n", [m])
To clear all key/value pairs from a map, you would simply reassign to an empty map.
m = #{},
io:format("Map: ~p~n", [m])
The optional second return value when getting a value from a map indicates if the key was present in the map. This can be used to disambiguate between missing keys and keys with zero values like 0
or ""
. Here we didn’t need the value itself, so we ignored it.
{_, Prs} = maps:is_key("k2", m),
io:format("Prs: ~p~n", [Prs])
You can also declare and initialize a new map in the same line with this syntax:
N = #{"foo" => 1, "bar" => 2},
io:format("Map: ~p~n", [N])
The maps
module contains a number of useful utility functions for maps. For example, the following comparison checks if two maps are equal.
N2 = #{"foo" => 1, "bar" => 2},
if maps:equal(N, N2) -> io:format("N == N2~n") end.
Note that maps appear in the form #{k => v, k => v}
when printed with io:format
.
Running the code gives the following output:
Map: #{<<"k1">> => 7, <<"k2">> => 13}
V1: 7
V3: zero_value
Size: 2
Map: #{<<"k1">> => 7}
Map: #{}
Prs: false
Map: #{<<"bar">> => 2, <<"foo">> => 1}
N == N2
Next example: Functions.