Maps in Elixir
Maps are Elixir's built-in associative data type (sometimes called hashes or dicts in other languages).
To create an empty map, use the `%{}` syntax:
```elixir
m = %{}
Set key/value pairs using typical map[key] = value
syntax.
m = Map.put(m, "k1", 7)
m = Map.put(m, "k2", 13)
Printing a map with e.g. IO.inspect
will show all of its key/value pairs.
IO.inspect(m, label: "map")
Get a value for a key with map[key]
.
v1 = Map.get(m, "k1")
IO.inspect(v1, label: "v1")
If the key doesn’t exist, Map.get/3
can return a default value.
v3 = Map.get(m, "k3", 0)
IO.inspect(v3, label: "v3")
The built-in map_size
returns the number of key/value pairs when called on a map.
IO.inspect(map_size(m), label: "len")
The built-in Map.delete
removes key/value pairs from a map.
m = Map.delete(m, "k2")
IO.inspect(m, label: "map")
To remove all key/value pairs from a map, you can reinitialize it to an empty map.
m = %{}
IO.inspect(m, label: "map")
The optional third return value when getting a value from a map can be used to disambiguate between missing keys and keys with zero values like 0
or ""
. Here we didn’t need the value itself, so we ignored it with the underscore _
.
{_, prs} = Map.pop(m, "k2")
IO.inspect(prs, label: "prs")
You can also declare and initialize a new map in the same line with this syntax.
n = %{"foo" => 1, "bar" => 2}
IO.inspect(n, label: "map")
The Map
module contains a number of useful utility functions for maps.
n2 = %{"foo" => 1, "bar" => 2}
if Map.equal?(n, n2), do: IO.puts("n == n2")
Note that maps appear in the form %{"key" => "value"}
when printed with IO.inspect
.
$ iex maps.exs
map: %{"k1" => 7, "k2" => 13}
v1: 7
v3: 0
len: 2
map: %{"k1" => 7}
map: %{}
prs: false
map: %{"bar" => 2, "foo" => 1}
n == n2
Next example: Functions.