Uses of Maps

Let’s learn how to make use of pattern matching with maps.

When to use maps

While random access in lists is relatively slow, random access in maps is O(logn)O(log n), significantly faster than O(n)O(n) for lists. Updating is also O(logn)O(log n). Whenever possible, any data we’ll heavily edit should be in a map, and data with unique values must be in a map. Maps also work very well with core Elixir concepts. Let’s see how.

Pattern matching

The map datatype and pattern matching are two of the most iconic parts of Elixir, and are even stronger in combination. The Elixir community is full of developers who have made the trek from object-oriented programming. Most of them at one time or another try to find a way to replicate inheritance, a way to share behavior across parts of a program. They are looking for polymorphism, or a way to write behaviors that work differently for the same data structure. Elixir can simulate polymorphism by explicitly matching map types with pattern matching.

Let’s say we have a struct called Animal. We’ll enter it in iex like this:

Executable

Get hands-on with 1200+ tech skills courses.