Intro
Once of interesting features of Elixir is pattern matching. That is way to save your time and similar the way we thinking.
Pattern matching is way to check equal value, extract value from tuple, list, map and binary.
How to uses
Pattern matching always return variable (term) for us can continue using it for other expression.
Three things we need to care in here:
- If not match it will raise an error.
- Pattern matching is always return original term (variable).
- If we add a variable for extracting, after matched variable will have value follow format we expected.
No we go to two use cases for using pattern matching.
check similar(condition) value
This type of pattern matching can help us verify a value, format of variable/param.
re
Simple we can check a atom like:
a = :an_atom
b = 1_000
c = {:ok, 1} # ... # use case 1
:an_atom = a
1_000 = b
{:ok, 1} = c # use case 2
case a do :an_atom -> :ok _other -> :nok
end case b do 1_000 -> :default _ -> :user_config
end # use case 3
check_ok = fn :ok -> true _ -> false
end result = check_ok.(a)
For case check equal value, that usually uses for verifying value, condition for branch code in function/case do.
If variable is complex term
example a tuple, list, map. We can discard other values to check one or more values we want.
Example:
list = [1, :a, "hello"]
tuple = {:ok, :a, 1}
map = %{a: 1, b: "hello"} # check first item of list is 1.
[1|_] = list # or ^list = [1|_] # check tuple has same values.
copy = ^tuple = {:ok, :a, 1} # check tuple has same number of elements.
{_, _, _} = tuple # check map has a key = :a and value of key = 1.
%{a: 1} = map
Extracting value
This feature of pattern matching help us can extract one or more value from a complex term
.
Remember, our expected value will bind to variable follow format of our pattern or key in map case.
(expression of pattern matching:
{:ok, get_value} = {:ok, “hello”}.
after matched, we got “hello” value from original term
)
Example:
tuple = {:ok, "hello"}
list = [:a, :b, 1, 2]
complex = {:ok, [{:first, 1}, {:second, [1, 2, 3]}]} # extract second element of tuple
{:ok, value} = tuple # get first item in list
[firt|_] = list # get second item in list
[_, second|_] = list # get value of result
{:ok, [{_, first_value}, {:second, second_value}]} = complex
We can use all key of example for function like:
defmodule Example do def return_second([_, second|_]) do # do something with second item. end def extract_map(%{a: value} = map) do # do some thing with value & map. end
end
works with binary/bitstring
This is interesting way to work with binary in Elixir. I wish other languages have this feature.
(I will add this later)
Discover more from Coursity
Subscribe to get the latest posts sent to your email.