Maps sind eine Datenstruktur, die Schlüssel-Wert-Paare enthält.
Schlüssel können von beliebigem Typ sein, müssen aber eindeutig sein.
Werte können von beliebigem Typ sein, sie müssen nicht eindeutig sein.
Maps garantieren nicht die Reihenfolge ihrer Inhalte, obwohl es den Anschein hat.
Maps können mit einer Literalform deklariert werden:
# 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}
Maps können auch mit Map.new aus dem Map-Modul erstellt werden. Das kann nützlich sein, wenn du bereits eine aufzählbare Sammlung hast, die du in eine Liste umwandeln möchtest:
kw_list = [a: 1, b: 2]
Map.new(kw_list)
# => %{a: 1, b: 2}
Auf Werte in einer Map kann auf viele verschiedene Arten zugegriffen werden:
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"
Das Map-Modul, das zur Standardbibliothek gehört, bietet viele nützliche Funktionen für die Arbeit mit Maps.
Map.delete(%{a: 2, b: 3}, :a)
# => %{b: 3}
Maps implementieren das Protokoll Enumerable, wodurch du Funktionen des Enum-Moduls verwenden kannst.
Anonyme Funktionen oder Referenzen auf eingefangene Funktionen werden oft als Argumente für Funktionen des Map- und des Enum-Moduls benötigt
# 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}]