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:
Set key/value pairs using typical map syntax.
Printing a map with io:format
will show all of its key/value pairs.
Get a value for a key with maps:get(Key, Map)
.
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
.
The maps:size
returns the number of key/value pairs in the map.
To remove key/value pairs from a map, use maps:remove/2
.
To clear all key/value pairs from a map, you would simply reassign to an empty map.
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.
You can also declare and initialize a new map in the same line with this syntax:
The maps
module contains a number of useful utility functions for maps. For example, the following comparison checks if two maps are equal.
Note that maps appear in the form #{k => v, k => v}
when printed with io:format
.
Running the code gives the following output:
Next example: Functions.