An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
Elixir pattern matching in a nutshell
Pattern matching in a nutshell
If you are new to Elixir, Pattern Matching may be something strange to you. When you get familiar with it, you will know how powerful it is. And I'm sure that you will definite love it.
Pattern matching is used everywhere in your elixlir code . And I would bring it to other language that I use ( if I can :D)
But it's not so hard.
What does Pattern Matching do?
Give you a variable/value, you might want
- Check if data type is match your expected data type
- Check if structure of data match your expected data structure
- Assign matching part of data to a variable
And pattern matching do all these thing for you. Just look at some example.
When you try these example, it will raise exception if data doesn't match against the pattern. In real Elixir app, you won't use it this way, check Where it is used at the end of this article
Pattern matching with Map/Struct
Check if this data is a map
%{} = params
Check if data is a map and has key email
and email value is [email protected]
%{"email" => "[email protected]"} = params
Check if data is a map and has key email
, if matchs pattern, assign value of key email
to variable my_email
%{"email" => my_email} = params
Check if data is a map and has key email
, I don't want to extract value
use _
to ignore value
%{"email" => _} = params
Pattern matching nested map
%{"address" => %{"city" => city}} = params
Check if data is type struct User
%User{} = params
The rest is same with map. Struct is basically a map with atom key.
Pattern matching with List
Check if data is empty lis
[] = params
Check if data is a list and not empty
[_|_] = params
Check if data is exact list
[1, 2] = params
Check if data is list and extract first element and remaining
[first_element | remaining] = params
Pattern matching with Tuple
You don't have much pattern to match against tuple
Check if data is tuple of 2 elements
{_, _} = params
Check if data is tuple and has specific value
{:ok, data} = result# you use this most of time
Where to use pattern matching
case clause
case user do %User{is_active: true} -> "Log you in" %User{is_active: false} -> "Check your email" _others -> "Not a user"end
with clause
with {:ok, user} <- create_user(params) do # your codeend
function
def is_admin(%User{role: "admin"}), do: truedef is_admin(%User{role: _}), do: falsedef is_admin(_), do: raise "Not a user"
Original Link: https://dev.to/bluzky/elixir-pattern-matching-in-a-nutshell-5fef
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To