マップは、キーと値のペアを保持するデータ構造です。
キーはどんな型でも構いませんが、一意でなければなりません。
値もどんな型でも構いません。一意である必要はありません。
マップは、そのように見えることがあるものの、内容の順序を保証しません。
マップはリテラル形式で宣言できます。
# 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}
マップは、MapモジュールのMap.newを使って生成することもできます。すでにマップに変換したい列挙可能なコレクションがある場合に使えます。
kw_list = [a: 1, b: 2]
Map.new(kw_list)
# => %{a: 1, b: 2}
マップの値には、さまざまな方法でアクセスできます。
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"
標準ライブラリに含まれるMapモジュールには、マップを扱うための便利な関数がたくさんあります。
Map.delete(%{a: 2, b: 3}, :a)
# => %{b: 3}
マップはEnumerableプロトコルを実装しているので、Enumモジュールの関数を使えます。
Mapや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}]