Overview
Elixir is a dynamic, functional language designed for building scalable and maintainable applications.
Elixir leverages the Erlang VM, known for running low-latency, distributed and fault-tolerant systems, while also being successfully used in web development and the embedded software domain.
Elixir Maps
Maps are the "go to" key-value data structure in Elixir. Maps can be created with the %{}
syntax, and key-value pairs can be expressed as key => value
:
iex> %{}
%{}
iex> %{"one" => :two, 3 => "four"}
%{3 => "four", "one" => :two}
Key-value pairs in a map do not follow any order (that's why the printed map in the example above has a different order than the map that was created).
Maps do not impose any restriction on the key type: anything can be a key in a map. As a key-value structure, maps do not allow duplicated keys. Keys are compared using the exact-equality operator (===/2
). If colliding keys are defined in a map literal, the last one prevails.
Being a functional programming language, Elixir is a bit different from other languages when it comes to update a nested data structure.
For example, in javascript we could do:
data = {
inner: {
one: {
a: 1
},
two: {
b: 45
}
}
}
data.inner.one.a = 2
In Elixir you have to build a new map with the updated information, for example:
data = %{
inner: %{
one: %{
a: 1
},
two: %{
b: 45
}
}
}
new_one = %{data.inner.one | a: 2}
new_inner = %{data.inner | one: new_one}
new_data = %{data | inner: new_inner}
which is not very handy.
In other functional languages like Haskell, there are libraries like Lenses
that aims to solve the problem. In Elixir the kernel have an put_in
function that acts in a similar way:
data = put_in(data, [:inner, :one, :a], 2)
You can find other similar functions in the Kernel documentation
Categories: #Elixir Tags: #Programming #Elixir #Data Structures #Elixir Maps #Erlang VM