In Elixir, the traditional assignment operator found in most languages is replaced by the match operator, denoted by =
. This match operator serves as the entry point for pattern matching, a core feature of the language.
Pattern matching in Elixir is deeply integrated into the BEAM runtime, ensuring efficient performance even when handling a multitude of pattern clauses. This design allows developers to leverage pattern matching without concerns about detrimental impacts on application performance.
This post will explore various pattern-matching syntaxes for fundamental data types, lists, maps, and tuples in Elixir.
Matching Lists:
# Matching a single element list
[a] = [1]
IO.inspect(a) # Output: 1
# Matching a tuple with multiple elements
[first | rest] = [1, 2, 3, 4]
IO.inspect(first) # Output: 1
IO.inspect(rest) # Output: [2, 3, 4]
# Matching specific elements in a list
[first, second | _] = [1, 2, 3, 4]
IO.inspect(first) # Output: 1
IO.inspect(second) # Output: 2
Matching Tuples:
# Matching a tuple
{:ok, result} = {:ok, "success"}
IO.inspect(result) # Output: "success"
# Matching specific elements in a tuple
{a, b, c} = {1, 2, 3}
IO.inspect(a) # Output: 1
IO.inspect(b) # Output: 2
IO.inspect(c) # Output: 3
Matching Maps:
# Matching a map
%{a: value_a, b: value_b} = %{a: 1, b: 2}
IO.inspect(value_a) # Output: 1
IO.inspect(value_b) # Output: 2
# Matching nested maps
%{key: %{nested_key: nested_value}} = %{key: %{nested_key: "nested"}}
IO.inspect(nested_value) # Output: "nested"
One key difference between matching lists and matching maps is that maps are loosely matched but lists are strictly matched. In other words, map matching behaves differently than lists because maps do not have to perfectly match.
# Maps do not have to perfectly match unlike lists
%{a: a} = %{a: 1, b: 2}
IO.inspect(a) # Output: 1
These simple examples showcase how pattern matching can be used to destructure and extract values from lists, tuples, and maps in Elixir.