Tuples
Mix.install([
{:jason, "~> 1.4"},
{:kino, "~> 0.8.0", override: true},
{:youtube, github: "brooklinjazz/youtube"},
{:hidden_cell, github: "brooklinjazz/hidden_cell"}
])
Navigation
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.
Review Questions
Upon completing this lesson, a student should be able to answer the following questions.
- What is a tuple and how do you create one?
- How do you pattern match on a tuple to bind elements in the tuple to variables?
Tuples
Tuples are fixed size containers for multiple elements. Like lists they can contain any data type.
{}
{7}
{1, 2, 3}
{"example"}
{1, "pizza", 3, :success, false}
They are often used when you know the number of desired elements and their type. For example, it’s common in Elixir to use tuples to represent failure or success cases with the associated error message or success value.
{:success, "Well done!"}
{:error, "Too bad!"}
Your Turn
In the Elixir cell below, create a tuple with :ok as the first element, and "got it!" as
the second element.
Example solution
{:ok, "got it!"}
Pattern Matching
In Elixir, the = sign is the match operator. In other programming languages, you may call it the assignment operator.
Elixir calls = the match operator because it uses pattern matching to bind variables.
What is pattern matching? Well rather than simply assigning values to variables, Elixir allows
you to bind variables on the left-hand side of the =. So long as it matches the same shape of the right hand side of the =.
For example, the following expression is the most “strict” match possible. Both sides are exactly equal.
{1, 2, 3} = {1, 2, 3}
The = operator attempts to coerce the left side value to match the right side value, so when we write the following expression, we bind my_tuple to {1, 2, 3} in order to make the right and the left side match.
The coercion to match is less obvious with a simple variable name, because it’s like a blank canvas, it can match any value.
my_tuple = {1, 2, 3}
However, we can bind other values inside of a container data type, so the left and right side still match.
{one, two, three} = {1, 2, 3}
Now we can use these bound variables one, two, and three in our program.
one
two
three
So long as the expression on the left side of match operator = matches the pattern of the right side, you can bind variables to values.
The tuple with variables bound on the left side must have the same number of elements as the tuple on the right side, otherwise we’ll cause a MatchError.
{one, two} = {1, 2, 3}
If we want to bind some of the variables in a tuple, and ignore others, we can use an _ to ignore any variables.
{one, _two, three} = {1, 2, 3}
You can pattern match with any kind of data. So long as the left side matches the right side. We’ll cover pattern matching with other data structures in later reading material.
Your Turn
Use pattern matching to bind "jewel" to a variable called jewel.
Replace jewel with your answer.
Example solution
{_gold, _treasure, jewel} = {"gold", "treasure", "jewel"}
jewel
{"gold", "treasure", "jewel"}
Further Reading
Consider the following resource(s) to deepen your understanding of the topic.
Mark As Completed
file_name = Path.basename(Regex.replace(~r/#.+/, __ENV__.file, ""), ".livemd")
save_name =
case Path.basename(__DIR__) do
"reading" -> "tuples_reading"
"exercises" -> "tuples_exercise"
end
progress_path = __DIR__ <> "/../progress.json"
existing_progress = File.read!(progress_path) |> Jason.decode!()
default = Map.get(existing_progress, save_name, false)
form =
Kino.Control.form(
[
completed: input = Kino.Input.checkbox("Mark As Completed", default: default)
],
report_changes: true
)
Task.async(fn ->
for %{data: %{completed: completed}} <- Kino.Control.stream(form) do
File.write!(
progress_path,
Jason.encode!(Map.put(existing_progress, save_name, completed), pretty: true)
)
end
end)
form
Commit Your Progress
Run the following in your command line from the curriculum folder to track and save your progress in a Git commit.
Ensure that you do not already have undesired or unrelated changes by running git status or by checking the source control tab in Visual Studio Code.
$ git checkout -b tuples-reading
$ git add .
$ git commit -m "finish tuples reading"
$ git push origin tuples-reading
Create a pull request from your tuples-reading branch to your solutions branch.
Please do not create a pull request to the DockYard Academy repository as this will spam our PR tracker.
DockYard Academy Students Only:
Notify your teacher by including @BrooklinJazz in your PR description to get feedback.
You (or your teacher) may merge your PR into your solutions branch after review.
If you are interested in joining the next academy cohort, sign up here to receive more news when it is available.
Up Next
| Previous | Next |
|---|---|
| Atoms | Lists |