TL;DR
In the previous post, we explained the Elixir Immutability concept. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.
Map
The map data structure in Elixir has not been named a map by chance. The everyday Map is a list of key/value pairs, where the key is location address, and value is GPS coordinates. This is Elixir Map record for Zagreb coordinates:
We created a map with Zagreb GPS coordinates. Then we stored that Map in variable so we could get coordinate values by key. Map could have any number of key/value pairs, as in the last example of :zagreb
and :new_york
GPS coordinates.
The Map is the module for map manipulations. The most used functions from that module are:
get
fetch
put
It is essential to note the difference between get
and fetch
, when key
was not found, get
returns nil
and fetch
returns :error
value. Very important for error handling.
Map Data Pattern
The Map is used to describe a record of data. Usually, this is a row from a database table. We use a special syntax where all keys are atoms.
We first defined comedian where keys
are atoms
. Then we accessed existing and none existing key. In the end, we updated :show
key and got new comedian2, while the comedian was unchanged due to Elixir’s immutability property.
Map in data pattern is usually defined with all keys
while keys
without value at that time are set with nil
value.
Remember
- for which data we use Maps
- difference between
get
andfetch
methods - how to use
put
- other Map module functions
- Map data pattern
- How to update Map with
|
operator.