Friday, December 29, 2017

Elixir: Pattern Matching - A Taste of Functional Programming

= is a match operator
After an initial assignment it then becomes a match assertion.
num = 1

To check the match assertion you can try this and it will be valid
1 = num

Furthermore, these are also valid:
[1] = [1]
[num] = [num]

Destructuring
[score1, score2, score3] = [89, 93, 87]
IO.puts score1  # 89
IO.puts score2  # 93
IO.puts score3  # 87

{:ok, value} = {:ok, 1000}
IO.puts value  # 1000

{:error, message} = {:error, "Uh oh"}
IO.puts message  # "Uh oh"

Error when matching:
{:foo, value} = {:bar, "nope"}

** (MatchError) no match of right hand side value: {:bar, "nope"}

Matching function arguments
Various function definitions and subsequent calls:
def sum_two_nums(num1, num2) do
  num1 + num2
end

sum_two_nums(2,5)


def sum_two_nums(%{num1: num1, num2: num2}) do
  num1 + num2
end

sum_two_nums(%{num1: 2, num2: 5})


def sum_two_nums([num1, num2]) do
  num1 + num2
end

sum_two_nums([2,5])

There's so much more you can do with pattern matching. It is one of the most powerful features you will learn and use when programming in Elixir.


Other posts in this series:

No comments:

Post a Comment