Elixir - Maps
Whenever you need a key-value store, maps are the “go to” data structure in Elixir. A map is created using the
Compared to keyword lists, we can already see two differences:
- Maps allow any value as a key.
- Maps’ keys do not follow any ordering.
In contrast to keyword lists, maps are very useful with pattern matching. When a map is used in a pattern, it will always match on a subset of the given value:
As shown above, a map matches as long as the keys in the pattern exist in the given map. Therefore, an empty map matches all maps.
Variables can be used when accessing, matching and adding map keys:
The Map module provides a very similar API to the
Keyword module with convenience functions to manipulate maps:
Maps have the following syntax for updating a key’s value:
The syntax above requires the given key to exist. It cannot be used to add new keys. For example, using it with the
:c key failed because there is no
:c in the map.
When all the keys in a map are atoms, you can use the keyword syntax for convenience:
Another interesting property of maps is that they provide their own syntax for accessing atom keys:
Elixir developers typically prefer to use the
map.field syntax and pattern matching instead of the functions in the
Map module when working with maps because they lead to an assertive style of programming. This blog post by José Valim provides insight and examples on how you get more concise and faster software by writing assertive code in Elixir.
Nested data structures
Often we will have maps inside maps, or even keywords lists inside maps, and so forth. Elixir provides conveniences for manipulating nested data structures via the
update_in/2 and other macros giving the same conveniences you would find in imperative languages while keeping the immutable properties of the language.
Imagine you have the following structure:
We have a keyword list of users where each value is a map containing the name, age and a list of programming languages each user likes. If we wanted to access the age for john, we could write:
It happens we can also use this same syntax for updating the value:
update_in/2 macro is similar but allows us to pass a function that controls how the value changes. For example, let’s remove “Clojure” from Mary’s list of languages:
There is more to learn about
update_in/2, including the
get_and_update_in/2 that allows us to extract a value and update the data structure at once. There are also
get_and_update_in/3 which allow dynamic access into the data structure.
This concludes our introduction to associative data structures in Elixir. You will find out that, given keyword lists and maps, you will always have the right tool to tackle problems that require associative data structures in Elixir.comments powered by Disqus