The Elixir programming language effectively uses pattern matching. Pattern matching is the process of checking that a left-side expression matches the expression’s right-side. This pattern matching assigns variables to data in lists, tuples, and hashmaps. Here is an example of matching a person’s name and age to variables, name
and age
:
[name, age] = ["John", 24]IO.puts name # JohnIO.puts age # 24
Elixir ships with guards that improve pattern matching or are used for a specific type of pattern matching. The hd
guard in Elixir returns a list’s head. Lists in Elixir are linked lists, and the head of a linked list is its first element. Here is an example use case of hd
:
fruits = ["Orange", "Apple", "Banana", "Melon"]IO.puts hd(fruits) # OrangeIO.puts hd([2, 3, 5, 7, 11]) # 2
An argument error is thrown when an empty list is passed to hd
since empty linked lists do not have a head.
IO.puts hd([]) # ArgumentError
Generally, a linked list is a recursive data structure with heads and tails. We can see this here:
head | tail1 2 3 4 5# And the tail is composed ofhead | tail2 3 4 5
This means an Elixir list like [1, 2, 3, 4, 5]
can be represented as [1 | [2, 3, 4, 5]]
. The hd
guard can also be used in such cases. When used on the list above, it returns 1
as the head.
IO.puts hd([1 | [2, 3, 4, 5]]) # 1