Pattern Matching in Elixir

Published September 24, 2018 by Toran Billups

Earlier this year I started learning Elixir but for whatever reason I didn't blog about it or write much software to document the learning process. In the past when I would learn something new I'd jump into code and build something straight away. This time around I decided to stretch myself and learn only by reading about the language, platform and ecosystem.

I'm finally making my way back to the language after a few months off and decided I would blog about my experience. I'll be reading the programming elixir 1.6 book from Dave Thomas and taking notes. Unlike my previous writing style I plan to make this go round less formal so I can focus more on the language and my journey through it.

Pattern Matching

The equals operator in Elixir is not about assignment, but rather matching. It succeeds if Elixir can find a way to make the left side equal the right side.

    a = 1

Elixir can make the match true by binding the variable `a` to value 1

    a = 1
    1 = a
    2 = a

The last statement above results in a match error. it's like asserting 2 = 1

Also, Elixir will only change the value of the variable on the left side of an equal sign.

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

Variables will bind only once per match

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

The last statement above results in a match error because `b` cannot have 2 different values.

After you assign a variable the value will never change (immutability at work). But you will find that Elixir lets you re-bind that variable.

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

You could force Elixir not to re-bind a variable by using the pin operator.

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

This statement would result in a match error if `a` was already assigned the value of 1

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

This statement would NOT result in a match error if `a` was already assigned the value of 1

Twitter / Github / Email