SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Downloaden Sie, um offline zu lesen
Александр Хохлов
@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)
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
Функции
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)
Хардкор
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
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

Front-End Developers Can Makes Games, Too!
Front-End Developers Can Makes Games, Too!Front-End Developers Can Makes Games, Too!
Front-End Developers Can Makes Games, Too!FITC
 
Ping pong game
Ping pong  gamePing pong  game
Ping pong gameAmit Kumar
 
Five things for you - Yahoo developer offers
Five things for you - Yahoo developer offersFive things for you - Yahoo developer offers
Five things for you - Yahoo developer offersChristian Heilmann
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPaweł Dawczak
 
Bringing Characters to Life for Immersive Storytelling - Dioselin Gonzalez
Bringing Characters to Life for Immersive Storytelling - Dioselin GonzalezBringing Characters to Life for Immersive Storytelling - Dioselin Gonzalez
Bringing Characters to Life for Immersive Storytelling - Dioselin GonzalezWithTheBest
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubySlaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubyJason Yeo Jie Shun
 
201412 seccon2014 オンライン予選(英語) write-up
201412 seccon2014 オンライン予選(英語) write-up201412 seccon2014 オンライン予選(英語) write-up
201412 seccon2014 オンライン予選(英語) write-up恵寿 東
 
Building Your First Widget
Building Your First WidgetBuilding Your First Widget
Building Your First WidgetChris Wilcoxson
 
Dirty Durham: Dry cleaning solvents leaked into part of Trinity Park | News
Dirty Durham: Dry cleaning solvents leaked into part of Trinity Park | NewsDirty Durham: Dry cleaning solvents leaked into part of Trinity Park | News
Dirty Durham: Dry cleaning solvents leaked into part of Trinity Park | Newsdizzyspiral5631
 
Возможности, особенности и проблемы AR::Relation
Возможности, особенности и проблемы AR::RelationВозможности, особенности и проблемы AR::Relation
Возможности, особенности и проблемы AR::RelationАлександр Ежов
 
Bloqueador cmd-sh
Bloqueador cmd-shBloqueador cmd-sh
Bloqueador cmd-shmsbertoldi
 
Node meetup feb_20_12
Node meetup feb_20_12Node meetup feb_20_12
Node meetup feb_20_12jafar104
 
jQuery for Beginners
jQuery for Beginners jQuery for Beginners
jQuery for Beginners NAILBITER
 
Shkrubbel for Open Web Camp 3
Shkrubbel for Open Web Camp 3Shkrubbel for Open Web Camp 3
Shkrubbel for Open Web Camp 3kitthod
 

Was ist angesagt? (20)

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

Ähnlich wie Pattern matching in Elixir by example - Alexander Khokhlov

Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05cKaz Yoshikawa
 
Cheap frontend tricks
Cheap frontend tricksCheap frontend tricks
Cheap frontend tricksambiescent
 
The report of JavaOne2011 about groovy
The report of JavaOne2011 about groovyThe report of JavaOne2011 about groovy
The report of JavaOne2011 about groovyYasuharu Nakano
 
Visual Component Testing -- w/ Gil Tayar (Applitools) and Gleb Bahmutov (Cyp...
Visual Component Testing  -- w/ Gil Tayar (Applitools) and Gleb Bahmutov (Cyp...Visual Component Testing  -- w/ Gil Tayar (Applitools) and Gleb Bahmutov (Cyp...
Visual Component Testing -- w/ Gil Tayar (Applitools) and Gleb Bahmutov (Cyp...Applitools
 
SVCC 2013 D3.js Presentation (10/05/2013)
SVCC 2013 D3.js Presentation (10/05/2013)SVCC 2013 D3.js Presentation (10/05/2013)
SVCC 2013 D3.js Presentation (10/05/2013)Oswald Campesato
 
Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02Omar Miatello
 
Phoenix for laravel developers
Phoenix for laravel developersPhoenix for laravel developers
Phoenix for laravel developersLuiz Messias
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemJohn De Goes
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012Nicholas Zakas
 
Django tips and_tricks (1)
Django tips and_tricks (1)Django tips and_tricks (1)
Django tips and_tricks (1)andymccurdy
 
Ruby to Elixir - what's great and what you might miss
Ruby to Elixir - what's great and what you might missRuby to Elixir - what's great and what you might miss
Ruby to Elixir - what's great and what you might missTobias Pfeiffer
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
An Introduction to Jquery
An Introduction to JqueryAn Introduction to Jquery
An Introduction to JqueryPhil Reither
 

Ähnlich wie Pattern matching in Elixir by example - Alexander Khokhlov (20)

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

Mehr von Elixir Club

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

Mehr von Elixir Club (20)

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

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 

Kürzlich hochgeladen (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Pattern matching in Elixir by example - Alexander Khokhlov

  • 7. 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
  • 9.
  • 10. iex > a = 1 1 iex > 1 = a 1 iex > 2 = a ** (MatchError) no match of right hand side value: 1
  • 12. iex > b = 2 2 iex > b = 3 3 iex > ^b = 4 ** (MatchError) no match of right hand side value: 4 iex > ^b = 3 3
  • 14. 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"]
  • 15. 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"
  • 17. 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
  • 19.
  • 20. iex > defmodule Hello do ... > def hello(name) do ... > "Hello, #{name}" ... > end ... > end … skipped … iex > Hello.hello("point") "Hello, point"
  • 21. 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"
  • 22. def hello(:point) def hello("Alex" <> _) def hello([name1, name2 | _]) def hello(%{first_name: name}) def hello(_) def hello(_name)
  • 24.
  • 25. 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})
  • 26. def hello(%x{} = person) when x in [Person] do IO.puts("Hello, #{person.first_name}") end
  • 27. 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
  • 28. def hello() do result = case {:ok, "Successful!"} do {:ok, result} -> result {:error} -> "Shit:(" _ -> "Catch all" end # result == "Successful!" end
  • 29. 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
  • 30. 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
  • 31.
  • 32. 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
  • 33. 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
  • 34.
  • 35. 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
  • 36. 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