Tracks
/
Elixir
Elixir
/
Syllabus
/
Pattern Matching
Pa

Pattern Matching in Elixir

68 exercises

About Pattern Matching

When writing Elixir functions, we can make use of an assertive style with pattern matching:

def read_file() do
  {:ok, contents} = File.read("hello.txt")
  contents
end
  • Pattern matching is explicitly performed using the match operator, =/2.

    • Matches succeed when the shape of the data on the left side of the operator matches the right side.

    • When matches succeed, variables on the left are bound to the values on the right.

    • Using an underscore, _, allows us to disregard the values in those places.

      {:ok, number, _} = {:ok, 5, [4.5, 6.3]}
      number
      # => 5 is bound to this variable
      
    • The pin operator ^ can be used to prevent rebounding a variable and instead pattern match against its existing value.

      number = 10
      {:ok, ^number, _} = {:ok, 5, [4.5, 6.3]}
      # => ** (MatchError) no match of right hand side value: {:ok, 5, [4.5, 6.3]}
      
  • Pattern matches may also occur in a function clause head, so that only arguments that match the pattern will invoke the function.

  • Variables can be bound in a function clause pattern match.

    defmodule Example do
      def named_function(:a = atom_variable) do
        {atom_variable, 1}
      end
    end
    
    Example.named_function(:a)
    # => {:a, 1}
    # The first function clause matches, so it is invoked
    
    Example.named_function(:b)
    # => ** (FunctionClauseError) no function clause matching in Example.named_function/1
    
Edit via GitHub The link opens in a new window or tab

Learn Pattern Matching

Practicing is locked

Unlock 10 more exercises to practice Pattern Matching