映射是一种保存键值对的数据结构。
键可以是任意类型,但必须唯一。
值可以是任意类型,不必唯一。
映射并不保证内容的顺序,尽管看起来好像会保证。
映射可以用字面量形式声明:
# 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}]