Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
About the Author
About the Reviewers

Using pattern matching

In some of the previous recipes, we've been using the = operator. When we execute something like a = 1, we are not performing an assignment; we are, instead, binding the value 1 to a.

This is actually pattern matching in its simplest form. The = operator is, in fact, called the match operator.

Getting ready

Start a new IEx session in your console.

How to do it…

To exercise our pattern matching techniques, we will follow these steps:

  1. Let's create a keyword list with our friends' birthdays:

    iex(1)> birthday_list = [andrew: "October 2nd", jim: "May 1st", carrie: "September 23rd", Carla: "August 30th"]
    [andrew: "October 2nd", jim: "May 1st", carrie: "September 23rd",carla: "August 30th"]
  2. Now, we will be getting the first element of the list (also known as head of the list):

    iex(2)> [head|tail] = birthday_list
    [andrew: "October 2nd", jim: "May 1st", carrie: "September 23rd",carla: "August 30th"]
    iex(3)> head
    {:andrew, "October 2nd"}
  3. All the other values (the tail of...