Le mappe sono una struttura dati che contiene coppie chiave-valore.
Le chiavi possono essere di qualsiasi tipo, ma devono essere uniche.
I valori possono essere di qualsiasi tipo, non devono essere unici.
Le mappe non garantiscono l'ordine del loro contenuto, anche se sembra il contrario.
Le mappe si possono dichiarare con una forma letterale:
# 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}
Le mappe si possono anche istanziare usando Map.new del modulo Map. Può essere utile se hai già una collezione enumerabile da trasformare in una lista:
kw_list = [a: 1, b: 2]
Map.new(kw_list)
# => %{a: 1, b: 2}
Ai valori di una mappa si può accedere in molti modi diversi:
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"
Il modulo Map, incluso nella libreria standard, ha molte funzioni utili per lavorare con le mappe.
Map.delete(%{a: 2, b: 3}, :a)
# => %{b: 3}
Le mappe implementano il protocollo Enumerable, il che permette di usare le funzioni del modulo Enum.
Spesso le funzioni del modulo Map e del modulo Enum richiedono come argomenti funzioni anonime o riferimenti a funzioni catturate
# 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}]