Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Pattern Matching

04-pattern-matching.livemd

Pattern Matching

Match Operator

We have already used match operator, its =

x = 1

in Elixir we can do something like this

1 = x # 1 and x are equal? 

It may look weird, because in JS you cant do this as = means only assignment to LHS

So appearently in ELixir this is different

Lets try to match it to another value

2 = x

Oh now it throws an error

2 = y

it seems that when you want to define a variable it should be assigned from LHS to RHS like JS but once assigned we call it as both holds an equality

So y = 10 means y will hold the value called 10

Matching existing values

Since = will rebound a variable on right side this happens

x = 1
x = 2 

Now how can we check if x is 1 if its on LHS?

for that elixir has ^, pin operator

x = 1
^x = 100000

Now it shows an error since x is pinned to the previously bounded value when comparision happens

Matching complex types

So its not just primitive values, you can match to anything

{name, age, hobbies} = {:kasun, 29, ["Anime", "Movies", "Workout"]}
name
age
hobbies

Lets try to match something which doesnt really make sense, a list and tuple

[a, b, c] = {:a, :b}

So it fails as expected.

We can also use pin(^) operator here

name = "Frodo"

{ ^name, race } = { "Sam", :hobbit }

Lists

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

Now we have a match for LHS and RHS and even we can access items inside a list

How cool 😎

We can also pattern match the head and tail of the list with [h | t] syntax

[head | tail] = [1, 2, 3, 4, 5, 6, 7, 8]
head
tail

if the list is actually empty…this fails as there is no way to match

[h | t] = []

Matching strings and binary data

In elixir its possible to even match strings and binary data with match operator which makes it so powerful

Strings

Look at the LHS and RHS carefully

"hello " <> subject = "hello WaveZync 🌊"

Now we can access subject 🤯

subject

Binary data

In elixir binary data represented as bitstrings, you can read more in docs

<> = "2024-11-01"
IO.inspect([year, month, day])

It means you can match a binary data packet coming through a wire and extract data 🤯

  • 8 bits = 1 byte
  • 16 bits = 2 bytes
<> = tcp_packet

This is just super cool right?