Tuesday, January 31, 2017

Elixir - Maps

Keyword lists are a convenient way to address content stored in lists by key, but underneath, Elixir is still walking through the list. That might be OK if you have other plans for that list requiring walking through all of it, but it can be unnecessary overhead if you’re planning to use keys as your only approach to the data.
This is where maps come to your rescue. Whenever you need a key-value store, maps are the “go to” data structure in Elixir.

Creating a map

A map is created using the %{} syntax:
map = %{:a => 1, 2 => :b}
Compared to keyword lists, we can already see two differences:
  • Maps allow any value as a key.
  • Maps’ keys do not follow any ordering.

Accessing a key

In order to acces value associated with a key, Maps use the same syntax as Keyword lists:
map = %{:a => 1, 2 => :b}
IO.puts(map[:a])
IO.puts(map[2])
When running above program, it produces following result:
1
b

Inserting a key

To insert a key in a map, we use Dict.put_new function which takes the map, new key and new value as arguments:
map = %{:a => 1, 2 => :b}
new_map = Dict.put_new(map, :new_val, "value") 
IO.puts(new_map[:new_val])
This will insert the key value pair :new_val - "value" in a new map. When running above program, it produces following result:
"value"

Updating a value

To update a value already present in the map, you can use the following syntax:
map = %{:a => 1, 2 => :b}
new_map = %{ map | a: 25}

IO.puts(new_map[:a])
When running above program, it produces following result:
25

Pattern Matching

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:
%{:a => a} = %{:a => 1, 2 => :b}
IO.puts(a)
This will match a with 1. And hence it'll generate the output as 1.
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:
n = 1
map = %{n => :one}
%{^n => :one} = %{1 => :one, 2 => :two, 3 => :three}
The Map module provides a very similar API to the Keyword module with convenience functions to manipulate maps. You can use Map.get, Map.delete, etc functions to manipulate maps.

Maps with Atom keys

Such maps have some interesting properties. When all the keys in a map are atoms, you can use the keyword syntax for convenience:
map = %{a: 1, b: 2}
Another interesting property of maps is that they provide their own syntax for updating and accessing atom keys:
map = %{:a => 1, 2 => :b}
IO.puts(map.a)
Note that to access atom keys in this way, it should exist or the program will fail to work.

No comments:

Post a Comment