맵은 키-값 쌍을 담는 자료 구조예요.
키는 어떤 타입이든 될 수 있지만, 고유해야 해요.
값도 어떤 타입이든 될 수 있고, 고유할 필요는 없어요.
맵은 내용의 순서를 보장하지 않아요. 순서가 있는 것처럼 보일 뿐이죠.
맵은 리터럴 형태로 선언할 수 있어요:
# 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}]