Los mapas son una estructura de datos que contiene pares de clave-valor.
Las claves pueden ser de cualquier tipo, pero deben ser únicas.
Los valores pueden ser de cualquier tipo, no tienen que ser únicos.
Los mapas no garantizan el orden de su contenido, aunque parezca que sí.
Los mapas se pueden declarar con una forma literal:
# An empty map
%{}
# A map with the atom key :a associated to the integer value 1
%{a: 1}
# A map with the string key "a" associated to the float value 2.0
%{"a" => 2.0}
# A map with the map key %{} with the list value [1 ,2, 3]
%{%{} => [1, 2, 3]}
# A map with keys of different types
%{:a => 1, "b" => 2}
Los mapas también se pueden instanciar usando Map.new del módulo Map. Esto puede servirte si ya tienes una colección enumerable que quieres convertir en una lista:
kw_list = [a: 1, b: 2]
Map.new(kw_list)
# => %{a: 1, b: 2}
Se puede acceder a los valores de un mapa de muchas maneras distintas:
my_map = %{key: "value"}
# with a dot if the key is an atom
my_map.key
# => "value"
# with [], a syntax provided by the Access behaviour
my_map[:key]
# => "value"
# with pattern matching
%{key: x} = my_map
x
# => "value"
# with Map.get/2
Map.get(my_map, :key)
# => "value"
El módulo Map, incluido en la biblioteca estándar, tiene muchas funciones útiles para trabajar con mapas.
Map.delete(%{a: 2, b: 3}, :a)
# => %{b: 3}
Los mapas implementan el protocolo Enumerable, lo que permite usar las funciones del módulo Enum.
A menudo se necesitan funciones anónimas o referencias a funciones capturadas como argumentos para las funciones de Map y del módulo Enum
# Increment the value by one, if it is not found, update it with 0
Map.update(%{a: 1}, :a, 0, &(&1 + 1))
# => %{a: 2}
# Sorting by a specific sub-value
list = [{"A", 4}, {"B", 3}, {"C", 2}, {"D", 1}]
Enum.sort_by(list, &Kernel.elem(&1, 1))
# => [{"D", 1}, {"C", 2}, {"B", 3}, {"A", 4}]