Maps
A map is a collection of key/value pairs. A map literal looks like this:
| %{ key => value, key => value } |
Here are some maps:
| iex> states = %{ "AL" => "Alabama", "WI" => "Wisconsin" } |
| %{"AL" => "Alabama", "WI" => "Wisconsin"} |
| |
| iex> responses = %{ { :error, :enoent } => :fatal, { :error, :busy } => :retry } |
| %{{:error, :busy} => :retry, {:error, :enoent} => :fatal} |
| |
| iex> colors = %{ :red => 0xff0000, :green => 0x00ff00, :blue => 0x0000ff } |
| %{blue: 255, green: 65280, red: 16711680} |
In the first case the keys are strings, in the second they’re tuples, and in the third they’re atoms. Although typically all the keys in a map are the same type, that isn’t required.
| iex> %{ "one" => 1, :two ... |
Get Programming Elixir ≥ 1.6 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.