Elixir Maps
A map is Elixir's key-value store. Keys can be any value (atoms, strings, numbers, even tuples), each key appears once, and lookups are fast. Maps are created with %{}.
prices = %{"apple" => 0.5, "bread" => 2.25, "milk" => 1.1}
IO.inspect(prices["bread"])
IO.inspect(prices["caviar"])
IO.inspect(map_size(prices))
point = %{x: 3, y: 4}
IO.inspect(point.x)
IO.inspect(point[:y])2.25
nil
3
3
4
There are two key syntaxes:
%{"apple" => 0.5}: the generalkey => valueform, for any key type.%{x: 3}: a shortcut when all keys are atoms (%{:x => 3}is the same map).
With atom keys you can use map.key. It raises KeyError if the key is missing, which catches typos early. map[key] returns nil for a missing key.
Updating maps
Maps are immutable, so "updating" returns a new map:
user = %{name: "Ravi", plan: :free, logins: 3}
upgraded = %{user | plan: :pro} # update existing key(s) only
IO.inspect(upgraded)
with_email = Map.put(user, :email, "ravi@example.com")
IO.inspect(Map.keys(with_email))
IO.inspect(Map.update(user, :logins, 1, &(&1 + 1)))
IO.inspect(Map.delete(user, :plan))
IO.inspect(user) # the original is unchanged
try do
%{user | age: 30}
rescue
e in KeyError -> IO.puts(Exception.message(e))
end%{name: "Ravi", plan: :pro, logins: 3}
[:name, :plan, :logins, :email]
%{name: "Ravi", plan: :free, logins: 4}
%{name: "Ravi", logins: 3}
%{name: "Ravi", plan: :free, logins: 3}
key :age not found
%{map | key: value} only works for keys that already exist, so it is the safe way to update fields. Map.put/3 adds or replaces any key. Map.update/4 applies a function to the current value (or inserts the default 1 if the key is missing).
The Map module
stock = %{"pens" => 40, "paper" => 0, "ink" => 12}
IO.inspect(Map.get(stock, "pens"))
IO.inspect(Map.get(stock, "staples", 0))
IO.inspect(Map.fetch(stock, "ink"))
IO.inspect(Map.has_key?(stock, "paper"))
IO.inspect(Map.merge(stock, %{"ink" => 20, "tape" => 5}))
IO.inspect(Map.filter(stock, fn {_item, qty} -> qty > 0 end))
IO.inspect(Map.to_list(%{b: 2, a: 1}) |> Enum.sort())40
0
{:ok, 12}
true
%{"ink" => 20, "paper" => 0, "pens" => 40, "tape" => 5}
%{"ink" => 12, "pens" => 40}
[a: 1, b: 2]
Iterating over a map
Enum functions treat a map as a collection of {key, value} tuples. The iteration order is not something to rely on, so sort when the order matters:
scores = %{"Mia" => 88, "Leo" => 95, "Ana" => 72}
scores
|> Enum.sort_by(fn {_name, score} -> -score end)
|> Enum.each(fn {name, score} -> IO.puts("#{name}: #{score}") end)
total = Enum.reduce(scores, 0, fn {_name, score}, acc -> acc + score end)
IO.puts("total: #{total}")
curved = Map.new(scores, fn {name, score} -> {name, min(score + 5, 100)} end)
IO.inspect(curved["Leo"])Leo: 95
Mia: 88
Ana: 72
total: 255
100
Note: The order in which a map's keys are printed or enumerated is an implementation detail: small maps (up to 32 keys) keep their keys in an internal sorted order, larger maps use a hash order, and atom keys are not even sorted alphabetically. Treat the order as undefined and sort when order matters.
Nested maps
Real data is often nested. get_in/2, put_in/2 and update_in/2 reach into nested structures:
config = %{
db: %{host: "localhost", port: 5432},
cache: %{ttl: 60}
}
IO.inspect(config.db.port)
IO.inspect(get_in(config, [:cache, :ttl]))
config = put_in(config.db.host, "db.internal")
config = update_in(config, [:cache, :ttl], &(&1 * 10))
IO.inspect(config.db)
IO.inspect(config.cache)5432
60
%{port: 5432, host: "db.internal"}
%{ttl: 600}
Pattern matching maps
A map pattern matches any map that has at least the given keys, which makes it great for function arguments:
greet = fn
%{name: name, lang: "pt"} -> "Olá, #{name}!"
%{name: name} -> "Hello, #{name}!"
end
IO.puts(greet.(%{name: "Bruno", lang: "pt", id: 7}))
IO.puts(greet.(%{name: "Kate"}))Olá, Bruno!
Hello, Kate!
Test yourself
What does %{a: 1}[:b] return?
- An error
nil0:error
What happens with %{m | new_key: 1} when m has no :new_key?
- The key is added
- A KeyError is raised
- It returns m unchanged
- It returns nil
Which map pattern matches %{id: 1, name: "x", age: 3}?
%{id: 1, name: n}%{id: 2}%{id: 1, email: e}- None: patterns must list every key