One of the cool things about Elixir is the pattern matching, in this post we will be able to understand about Pattern Matching and how works the pin operator “ ^”.

The pattern matching is a feature that Elixir brought from the Erlang and is a natural functional language. To make it easy see the following example:

iex> {:ok, foo} = {:ok, "hello"} {:ok, "hello"}

In this example, we are checking if the right side matches with the pattern from the left side. From the left side, we have a tuple with an atom element and a variable called “foo”.

What Elixir does is check the type and content of the two sides, in this case, we have two tuples on the left side the first value matches the right (:ok, :ok) and the second value (foo) matches the right because we have a variable that will be filled.

The pattern matching will throw an error if the values on either side do not coincide.

iex> {a, b, c} = [:hello, "world", "!"] ** (MatchError) no match of right hand side value: [:hello, "world", "!"]

We can use pattern matching with lists:

iex> [a, b, c] = [1, 2, 3] [1, 2, 3] iex> a 1

Or with function definitions:

defmodule Hello do def say_hello(:bob), do: "Hello, Bob!" def say_hello(:elixir), do: "Hello, Elixir!" def say_hello(name), do: "Hello, #{name}!" end # Hello.say_hello(:elixir) #=> "Hello, Elixir!" # Hello.say_hello("Mike") #=> "Hello, Mike!"

Bonus: Pattern matching with recursion.

defmodule MathRecursion do def sum([]) do 0 end def sum([head|tail]) do head + sum(tail) end end MathRecursion.sum([1,2,3]) #=> 6

Pin operator

The pin operator ^ should be used when you want to pattern match against an existing variable’s value rather than rebinding the variable…

So with pin operator we treat the variable like a literal value and rebind is disabled, see example:

x = 1 x = 2 ^x = 3 #=> ** (MatchError) no match of right hand side value: 3 a = 1 b = 2 {a, ^b} = {1, 2} #=> {1, 2} {a, ^b} = {1, 1} #=> ** (MatchError) no match of right hand side value: {1, 1}

So, in this post, I explained a little bit about pattern matching and how to use it in Elixir. The next posts I’ll show some more complex examples.

Learn You Some Erlang for Great Good!

Learn you some Erlang for great good! An Erlang tutorial for beginners and others too.learnyousomeerlang.com

Pattern matching – Elixir

In this chapter, we will show how the = operator in Elixir is actually a match operator and how to use it to pattern…elixir-lang.org