Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

The Go To Datastructure the MAP

elixier_notebooks/Maps.livemd

The Go To Datastructure the MAP

Maps in Elixir

In Elixir Maps are the Go-to key-value store. Unlike keyword lists, they allow keys of any type and are un-ordered. You can define a map with the %{} syntax:

map = %{:foo => "bar", "hello" => :world}
%{:foo => "bar", "hello" => :world}
map[:foo]
"bar"
map["hello"]
:world

As of Elixir 1.2, variables are allowed as map keys:

key = "hello"
%{key => "world"}
%{"hello" => "world"}

If a duplicate is added to a map, it will replace the former value:

%{:foo => "bar", :foo => "hello world"}
warning: key :foo will be overridden in map
  #cell:ydlln7yiremyforf:1
%{foo: "hello world"}

As we can see from the output above, there is a special syntax for maps containing only atom keys:

%{foo: "bar", hello: "world"}
%{hello: "world", foo: "bar"}
%{foo: "bar", hello: "world"} == %{:foo => "bar", :hello => "world"}
true

In addition, there is a special syntax you can use with atom keys:

map = %{foo: "bar", hello: "world"}
%{hello: "world", foo: "bar"}
map.hello
"world"

Another interesting property of maps is that they provide their own syntax for updates (note: this creates a new map):

map = %{foo: "bar", hello: "world"}
%{hello: "world", foo: "bar"}
%{map | foo: "baz"}
%{hello: "world", foo: "baz"}

Note: this syntax only works for updating a key that already exists in the map! If the key does not exist, a KeyError will be raised.

To create a new key, instead use Map.put/3

map = %{hello: "world"}
%{hello: "world"}
%{map | foo: "baz"}
Map.put(map, :foo, "baz")
%{hello: "world", foo: "baz"}