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.
To exercise our pattern matching techniques, we will follow these steps:
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"]
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"}
All the other values (the tail of...