When To Use Elixir Maps Data Structure — Tentamen Software Testing Blog

Image for post
Image for post
Image by Hans Braxmeier from Pixabay

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:

Image for post
Image for post
Elixir Map In Action

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:

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.

Image for post
Image for post
Map with atoms as keys

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

Originally published at https://blog.tentamen.eu on August 21, 2020.

Written by

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store