SlideShare a Scribd company logo
Александр Хохлов
@apoint
Pattern matching 

in Elixir by example
Founder at Nots
http://nots.io
TL;DR
https://images.techhive.com/images/article/2016/06/integration-projects-disasters-9-100669080-gallery.idge.jpg
https://twitter.com/bloerwald/status/448415935926255618
История
Erlang The Movie II: The Sequel
https://www.youtube.com/watch?v=rRbY3TMUcgQ
https://img00.deviantart.net/de6b/i/2011/044/b/9/erlang_the_movie_by_mcandre-d39hupa.png
Нет присваивания
(assignment)
Pattern matching in Elixir by example - Alexander Khokhlov
iex > a = 1
1
iex > 1 = a
1
iex > 2 = a
** (MatchError) no match of right hand side
value: 1
Переменные можно связывать
заново (rebind)
iex > b = 2
2
iex > b = 3
3
iex > ^b = 4
** (MatchError) no match of right hand side
value: 4
iex > ^b = 3
3
Можно сопоставлять
структуры данных
iex > {:ok, value} = {:ok, "Successful!"}
{:ok, "Successful!"}
iex > value
“Successful!”
iex > {:ok, value} = {:error, "Shit:("}
** (MatchError) no match of right hand side
value: {:error, “Shit:(“}
iex > {:ok, value} = [:ok, "Success"]
** (MatchError) no match of right hand side
value: [:ok, "Success"]
iex > %{key: value} = %{key: “hash value"}
%{key: “hash value"}
iex > value
“hash value”
iex > %{key1: value} = %{key1: "value1", key2: "value2"}
%{key1: "value1", key2: "value2"}
iex > value
“value1"
iex > key = :key1
:key1
iex > %{^key => value} = %{key1: "value1", key2: "value2"}
%{key1: "value1", key2: "value2"}
iex > value
"value1"
А еще списки
iex > list = [1, 2, 3]
[1, 2, 3]
iex > [1 | tail] = list
[1, 2, 3]
iex > tail
[2, 3]
iex > [2 | _] = list
** (MatchError) no match of right hand side
value: [1, 2, 3]
iex > [head | tail] = list
[1, 2, 3]
iex > head
1
Функции
Pattern matching in Elixir by example - Alexander Khokhlov
iex > defmodule Hello do
... > def hello(name) do
... > "Hello, #{name}"
... > end
... > end
… skipped …
iex > Hello.hello("point")
"Hello, point"
iex > defmodule Hello do
... > def hello(:point) do
... > "Greeting, my lord"
... > end
... > def hello(name) do
... > "Hello, #{name}"
... > end
... > end
iex > Hello.hello(:point)
"Greeting, my lord"
iex > Hello.hello("John")
"Hello, John"
def hello(:point)
def hello("Alex" <> _)
def hello([name1, name2 | _])
def hello(%{first_name: name})
def hello(_)
def hello(_name)
Хардкор
Pattern matching in Elixir by example - Alexander Khokhlov
iex > defmodule Person do
... > defstruct first_name: "", last_name: ""
... > end
iex > def hello(%Person{} = person) do
... > IO.puts("Hello, #{person.first_name}")
... > end
iex > Hello.hello(%Person{first_name: "Arthur",
last_name: "Dent"})
Hello, Arthur
def hello(%Person{first_name: first_name})
def hello(%x{} = person) when x in [Person] do
IO.puts("Hello, #{person.first_name}")
end
defmodule Person do
defstruct age: 0
end
defmodule Greeting do
def hello(%{age: age}) when 6 < age and age < 12, do:
"Hiya"
def hello(%{age: age}) when age in 12..18, do:
"Whatever"
def hello(%{age: age}) when 60 < age, do:
“You kids get off my lawn"
def hello(_), do: "Hello"
end
https://hexdocs.pm/elixir/master/guards.html
def hello() do
result = case {:ok, "Successful!"} do
{:ok, result} -> result
{:error} -> "Shit:("
_ -> "Catch all"
end
# result == "Successful!"
end
defmodule Factorial do
def of(0), do: 1
def of(n) when n > 0 do
n * of(n - 1)
end
end
iex > Factorial.of(10)
3628800
defmodule ImageTyper do
@png_signature <<137::size(8), 80::size(8), 78::size(8), 71::size(8),
13::size(8), 10::size(8), 26::size(8), 10::size(8)>>
@jpg_signature <<255::size(8), 216::size(8)>>
def type(<<@png_signature, rest::binary>>), do: :png
def type(<<@jpg_signature, rest::binary>>), do: :jpg
def type(_), do :unknown
end
Pattern matching in Elixir by example - Alexander Khokhlov
def create(params) do
case validate_name(params["name"]) do
{:ok, name} ->
case validate_email(params["email"]) do
{:ok, email} ->
create_db_record(name, email)
{:error, message} ->
conn |> put_flash(:error, "Wrong email: #{message}")
|> redirect(to: "/")
end
{:error, message} ->
conn |> put_flash(:error, "Wrong name: #{message}")
|> redirect(to: "/")
end
end
def create(params) do
with {:ok, name} <- validate_name(params["name"]),
{:ok, email} <- validate_email(params["email"])
do
create_db_record(name, email)
else
{:name_error, message} ->
conn |> put_flash(:error, "Wrong name: #{message}") |>
redirect(to: "/")
{:email_error, message} ->
conn |> put_flash(:error, "Wrong email: #{message}") |
> redirect(to: "/")
end
end
Pattern matching in Elixir by example - Alexander Khokhlov
defmodule MyAppWeb.PageController do
action_fallback MyAppWeb.FallbackController
def show(params) do
with {:ok, username} <- get_username(params),
{:ok, cms_page} <- CMS.get_page(username, params) do
render(conn, "show.html", page: page)
end
end
end
defmodule MyAppWeb.FallbackController do
def call(conn, {:username_error, message}) do
conn |> put_flash(:error, "Wrong usernname: #{message}") |> redirect(to: "/")
end
def call(conn, {:cms_page_not_found, message}) do
conn |> put_flash(:error, "Page not found: #{message}") |> redirect(to: "/")
end
end
defmodule NotsappWeb.ProjectsFallbackController do
use Phoenix.Controller
def call(conn, _) do
conn
|> put_status(:not_found)
|> put_layout(false)
|> render(NotsappWeb.ErrorView, :”501")
end
end
@apoint
point@nots.io
http://nots.io/jobs
@nots_io
facebook.com/nots.io

More Related Content

PDF
Slide
TXT
PDF
WordPress Security: Be a Superhero - WordCamp Raleigh - May 2011
TXT
R57.Php
PDF
Itsecteam shell
KEY
$.Template
PDF
Maze solving app listing
DOCX
A simple snake game project
Slide
WordPress Security: Be a Superhero - WordCamp Raleigh - May 2011
R57.Php
Itsecteam shell
$.Template
Maze solving app listing
A simple snake game project

What's hot (20)

PDF
Front-End Developers Can Makes Games, Too!
DOCX
Ping pong game
PDF
Five things for you - Yahoo developer offers
DOCX
Borrador del blog
RTF
PDF
Pre-Bootcamp introduction to Elixir
PDF
Bringing Characters to Life for Immersive Storytelling - Dioselin Gonzalez
PDF
jQuery: Events, Animation, Ajax
PDF
Undrop for InnoDB
PDF
Slaying the Dragon: Implementing a Programming Language in Ruby
PDF
201412 seccon2014 オンライン予選(英語) write-up
PPTX
Building Your First Widget
PDF
Dirty Durham: Dry cleaning solvents leaked into part of Trinity Park | News
PDF
Возможности, особенности и проблемы AR::Relation
TXT
Bloqueador cmd-sh
PDF
Node meetup feb_20_12
PDF
PPTX
jQuery for Beginners
DOC
PPTX
Shkrubbel for Open Web Camp 3
Front-End Developers Can Makes Games, Too!
Ping pong game
Five things for you - Yahoo developer offers
Borrador del blog
Pre-Bootcamp introduction to Elixir
Bringing Characters to Life for Immersive Storytelling - Dioselin Gonzalez
jQuery: Events, Animation, Ajax
Undrop for InnoDB
Slaying the Dragon: Implementing a Programming Language in Ruby
201412 seccon2014 オンライン予選(英語) write-up
Building Your First Widget
Dirty Durham: Dry cleaning solvents leaked into part of Trinity Park | News
Возможности, особенности и проблемы AR::Relation
Bloqueador cmd-sh
Node meetup feb_20_12
jQuery for Beginners
Shkrubbel for Open Web Camp 3
Ad

Similar to Pattern matching in Elixir by example - Alexander Khokhlov (20)

PDF
Idioms in swift 2016 05c
PDF
Cheap frontend tricks
PDF
The report of JavaOne2011 about groovy
PDF
Elixir cheatsheet
PDF
Visual Component Testing -- w/ Gil Tayar (Applitools) and Gleb Bahmutov (Cyp...
PPTX
Svcc 2013-d3
PPTX
SVCC 2013 D3.js Presentation (10/05/2013)
PPT
Python tutorial
PPTX
Android & Kotlin - The code awakens #02
PPTX
Es6 hackathon
PDF
Phoenix for laravel developers
PDF
The Design of the Scalaz 8 Effect System
PPTX
Maintainable JavaScript 2012
PDF
Python
PPTX
Django tips and_tricks (1)
PDF
Ruby to Elixir - what's great and what you might miss
ODP
AST Transformations at JFokus
PDF
Ruby Language - A quick tour
PDF
An Introduction to Jquery
Idioms in swift 2016 05c
Cheap frontend tricks
The report of JavaOne2011 about groovy
Elixir cheatsheet
Visual Component Testing -- w/ Gil Tayar (Applitools) and Gleb Bahmutov (Cyp...
Svcc 2013-d3
SVCC 2013 D3.js Presentation (10/05/2013)
Python tutorial
Android & Kotlin - The code awakens #02
Es6 hackathon
Phoenix for laravel developers
The Design of the Scalaz 8 Effect System
Maintainable JavaScript 2012
Python
Django tips and_tricks (1)
Ruby to Elixir - what's great and what you might miss
AST Transformations at JFokus
Ruby Language - A quick tour
An Introduction to Jquery
Ad

More from Elixir Club (20)

PDF
Kubernetes + Docker + Elixir - Alexei Sholik, Andrew Dryga | Elixir Club Ukraine
PDF
Integrating 3rd parties with Ecto - Eduardo Aguilera | Elixir Club Ukraine
PDF
— An async template - Oleksandr Khokhlov | Elixir Club Ukraine
PDF
BEAM architecture handbook - Andrea Leopardi | Elixir Club Ukraine
PDF
You ain't gonna need write a GenServer - Ulisses Almeida | Elixir Club Ukraine
PDF
— Knock, knock — An async templates — Who’s there? - Alexander Khokhlov | ...
PDF
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
PDF
Erlang cluster. How is it? Production experience. — Valerii Vasylkov | Elixi...
PDF
Promo Phx4RailsDevs - Volodya Sveredyuk
PDF
Web of today — Alexander Khokhlov
PDF
ElixirConf Eu 2018, what was it like? – Eugene Pirogov
PDF
Implementing GraphQL API in Elixir – Victor Deryagin
PDF
WebPerformance: Why and How? – Stefan Wintermeyer
PDF
GenServer in Action – Yurii Bodarev
PDF
Russian Doll Paradox: Elixir Web without Phoenix - Alex Rozumii
PDF
Practical Fault Tolerance in Elixir - Alexei Sholik
PDF
Phoenix and beyond: Things we do with Elixir - Alexander Khokhlov
PDF
Monads are just monoids in the category of endofunctors - Ike Kurghinyan
PDF
Craft effective API with GraphQL and Absinthe - Ihor Katkov
PDF
Elixir in a service of government - Alex Troush
Kubernetes + Docker + Elixir - Alexei Sholik, Andrew Dryga | Elixir Club Ukraine
Integrating 3rd parties with Ecto - Eduardo Aguilera | Elixir Club Ukraine
— An async template - Oleksandr Khokhlov | Elixir Club Ukraine
BEAM architecture handbook - Andrea Leopardi | Elixir Club Ukraine
You ain't gonna need write a GenServer - Ulisses Almeida | Elixir Club Ukraine
— Knock, knock — An async templates — Who’s there? - Alexander Khokhlov | ...
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Erlang cluster. How is it? Production experience. — Valerii Vasylkov | Elixi...
Promo Phx4RailsDevs - Volodya Sveredyuk
Web of today — Alexander Khokhlov
ElixirConf Eu 2018, what was it like? – Eugene Pirogov
Implementing GraphQL API in Elixir – Victor Deryagin
WebPerformance: Why and How? – Stefan Wintermeyer
GenServer in Action – Yurii Bodarev
Russian Doll Paradox: Elixir Web without Phoenix - Alex Rozumii
Practical Fault Tolerance in Elixir - Alexei Sholik
Phoenix and beyond: Things we do with Elixir - Alexander Khokhlov
Monads are just monoids in the category of endofunctors - Ike Kurghinyan
Craft effective API with GraphQL and Absinthe - Ihor Katkov
Elixir in a service of government - Alex Troush

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
KodekX | Application Modernization Development
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Cloud computing and distributed systems.
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Electronic commerce courselecture one. Pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Dropbox Q2 2025 Financial Results & Investor Presentation
KodekX | Application Modernization Development
Empathic Computing: Creating Shared Understanding
Digital-Transformation-Roadmap-for-Companies.pptx
Big Data Technologies - Introduction.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Cloud computing and distributed systems.
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Electronic commerce courselecture one. Pdf
Per capita expenditure prediction using model stacking based on satellite ima...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Approach and Philosophy of On baking technology
Programs and apps: productivity, graphics, security and other tools
Spectral efficient network and resource selection model in 5G networks
Chapter 3 Spatial Domain Image Processing.pdf
20250228 LYD VKU AI Blended-Learning.pptx

Pattern matching in Elixir by example - Alexander Khokhlov