Skip to content

Latest commit

 

History

History
334 lines (222 loc) · 7.66 KB

maps.livemd

File metadata and controls

334 lines (222 loc) · 7.66 KB

Maps

Mix.install([
  {:youtube, github: "brooklinjazz/youtube"},
  {:hidden_cell, github: "brooklinjazz/hidden_cell"},
  {:tested_cell, github: "brooklinjazz/tested_cell"},
  {:utils, path: "#{__DIR__}/../utils"}
])

Navigation

Return Home Report An Issue

Setup

Ensure you type the ea keyboard shortcut to evaluate all Elixir cells before starting. Alternatively, you can evaluate the Elixir cells as you read.

Maps

Maps are another type of associative data structure. In fact maps are the common go-to for a key-value data structure. You can create a map using %{}. Similar to keyword lists they can have atoms as keys and then any value.

%{key: "value"}

However, unlike keyword lists, keys must be unique; otherwise they will be overwritten. Elixir is very helpful and provides a warning to let us know we're overriding a duplicate key.

%{duplicate_key: "value1", duplicate_key: "value2"}

Unlike keyword lists, maps do not guarantee key order, which is why you'll notice the returned value of the map below does not have the same order as the map created.

%{one: "one", two: "two", three: "three"}

Unlike keyword lists, maps can have any values as the key. Commonly you will see atom-key maps

%{atom_key: "value"}

And also string-key maps.

%{"string key" => "value"}

However, the key to a map could be anything! Even another map! You will need to use the => symbol though, not a colon :. => is an equals sign = and a greater than symbol >.

%{[1,2,3] => "value"}
%{%{example: "my_example"} => "value"}
%{1 => "value"}

Accessing Map Values

Unlike the other data types, there aren't specific map operators. To manipulate maps we use a different tool called the Map module, which you will learn more about in a future lesson.

For now, it's enough to know that you can access values in an atom-key map using a few different methods.

You can retrieve values in a map using map.key notation like so. This only works for maps with atom keys.

%{key: "value"}.key

Alternatively, you can access the map value using square bracket notation map[key].

%{key: "value"}[:key]

Bracket notation is especially useful for maps with non-atom keys.

%{"key" => "value"}["key"]
%{1 => "value"}[1]

With map.key notation, your program will throw an error if your map doesn't have the expected value.

%{}.key

Bracket notation will return nil if the key doesn't exist rather than throwing an error.

%{}[:key]

We can access deeply nested values with both dot notation and bracket notation.

%{key1: %{key2: %{key3: "value"}}}.key1.key2.key3
%{1 => %{2 => %{3 => "value"}}}[1][2][3]

Bracket notation is especially useful for accessing deeply nested values without causing a crash if the value doesn't exist.

%{}[1][2][3]

You can accomplish all of the same behavior above by binding the map to a variable rather than accessing values from the map directly.

map = %{key: "value"}
map.key
map = %{key: "value"}
map[:key]

Your Turn

In the Elixir cell below, access the :hello key in map. Retrieve the value using both map[key] and map.key notation.

Example solution

map.key notation.

map = %{hello: "world"}
map.hello

map[] notation.

map = %{hello: "world"}
map[:hello]
map = %{hello: "world"}

Updating Maps

You can update values in a map using %{initial_map | updated_values} syntax like so.

initial = %{key: "value"}

%{initial | key: "new value"}

Elixir does not allow you to mutate values. That means the variable initial is still %{key: "value"}

initial

You can instead store a new variable for the updated map.

updated = %{initial | key: "new value"}
updated

Or rebind the existing initial variable.

initial = %{initial | key: "new value"}
initial

You can only update existing atom key values in a map, otherwise it will cause an error.

initial = %{}
%{initial | new_key: "value"}

Your Turn

Use a map to represent a todo item The todo map should have :title and :completed keys.

  • title: "finish maps exercises", completed: false

Bind your map to a todo variable, and update the value so completed is true.

Example solution
todo = %{title: "finish maps exercise", completed: false}

%{todo | completed: true}

Pattern Matching

We can pattern match on values inside the map.

%{hello: my_variable} = %{hello: "world"}
my_variable

Unlike with keyword lists, we don't have to match on every key/value pair when pattern matching with maps.

%{one: one} = %{one: 1, two: 2}
one

This also works with non-atom key maps.

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

We can only pattern match on the value in the map, not the key. Keys in maps must be literals such as atoms, strings, tuples, etc.

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

Pin Operator

You'll notice that we can rebind variables using pattern matching.

name = "Jon"

%{name: name} = %{name: "Bill"}

name

If instead of re-binding the variable, we want to use the literal value of the variable, we can use the pin operator ^.

name = "Jon"

%{name: ^name} = %{name: "Bill"}

name

The above causes a MatchError because the left side and right side do not match. It's the same as if we had written the following.

%{name: "Jon"} = %{name: "Bill"}

We might use this to confirm our map matches some shape.

Your Turn

Bind 2 and 4 in the following map to variables two and four.

Example solution
%{two: two, four: four} = %{one: 1, two: 2, three: 3, four: 4}

Enter your solution below.

%{one: 1, two: 2, three: 3, four: 4}

Further Reading

Consider the following resource(s) to deepen your understanding of the topic.

Commit Your Progress

Run the following in your command line from the beta_curriculum folder to track and save your progress in a Git commit.

$ git add .
$ git commit -m "finish maps section"

Up Next

Previous Next
Keyword Lists Shopping List