Pattern matching in Elixir

Pattern matching in Elixir

Elixir’s pattern matching shapes everything you program. It’s useful for assigning variables, unpacking values, and making decisions such as which function to invoke. The basis of pattern matching is that it tries to make two things match, and it does something when it fails to do so.

In Elixir, the = operator is called the match operator: The match operator is not only used to match against simple values, but it is also useful for destructuring more complex data types. For example, we can pattern match on tuples:

iex> {status, message, id} = {:ok, "hello, world", 42}
{:ok, "hello, world", 42}
iex> status
:ok

a MatchError would be raised if the tuples are of different sizes, or when comparing different types ie a tuple and a list.

You can pattern match on lists:

iex> [one, two, three] = [1, 2, 3]
[1, 2, 3]
iex> one
1
iex> [head | tail] = ["MON", "TUE", "WED", "THUR"]
["MON", "TUE", "WED", "THUR"]
iex> head
"MON"