SlideShare a Scribd company logo
ELIXIRCHEATSHEET
ECOSYSTEM,
FUNDAMENTAL
&RUNTIME
BENKHALFALLAHHÉLA
1.
ECOSYSTEM
Elixir is a dynamic & functional language.
iex : Elixir's interactive shell.
mix : build automation tool.
hex : package manager for the Erlang ecosystem.
COMMAND DESCRIPTION
mix new my_project Create new project
mix compile Compile project
MIX_ENV=prod mix compile Compile by env
Available envs: prod, dev
& test (default is dev)
iex -S mix + recompile Run project & reload on
each change
mix release Create release
MIX_ENV=prod mix release Create release by env
mix deps.get Add a dependency
mix hex.outdated Show outdated
dependencies
mix hex.audit Audit dependencies
mix do deps.get, deps.compile Multiple tasks
DOCUMENTATION
ExDoc: generate documentation
mix docs
https://hex.pm/packages/ex_doc
Inch: documentation coverage
mix inch
https://github.com/rrrene/inch_ex
CODEQUALITY
ExUnit : unit test
mix test
Excoveralls : unit test coverage
MIX_ENV=test mix coveralls
https://github.com/parroty/excoveralls
TAG DESCRIPTION
@moduledoc Module documentation
@doc Function documentation
@spec
@spec function_name (type1,
type2) :: return_type
Types spec documentation
COMMAND DESCRIPTION
mix format Code formatter
credo & dialyxir
mix credo --strict
mix dialyzer
Static code analysis
2.
FUNDAMENTAL
FILESEXTENSION
NAMINGCONVENTION
File snake_case
Module UpperCamelCase
Function snake_case
Variable snake_case
Unused
parameter
_foo
Atoms snake_case or UpperCamelCase
:true, :is_connected?, :debit_type_card
.ex : elixir file
.exs : elixir scripts file
DEFINITION
MODULE
defmodule ElixirPatternMatching do
// staff
end
FUNCTION
def sum(x,y) do
IO.inspect x
IO.inspect y
x + y # returned value
end
In Elixir, a function must be defined inside a module.
PRIVATEFUNCTION
defp get_gps_coordinates(country) do
%{
France: {46.71109, 1.7191036},
Spain: {40.2085, -3.713},
Italy: {41.29246, 12.5736108}
}[country]
end
PIPEOPERATOR
"Elixir rocks"
|> String.upcase()
|> String.split()
TYPECHECKS
is_atom/1
is_bitstring/1
is_boolean/1
is_function/1
is_function/2
is_integer/1
is_float/1
is_binary/1
is_list/1
is_map/1
is_tuple/1
is_nil/1
is_number/1
is_pid/1
is_port/1
is_reference/1
https://hexdocs.pm/elixir/Kernel.html#is_atom/1
INTEGEROPERATIONS
import Integer
n = 12
n
|> digits()
|> IO.inspect # → [1, 2]
n
|> to_charlist()
|> IO.inspect # → '12'
n
|> to_string()
|> IO.inspect # → "12"
n
|> is_even()
|> IO.inspect # true
n
|> is_odd()
|> IO.inspect # false
https://hexdocs.pm/elixir/Integer.html#content
FLOATOPERATIONS
import Float
n = 10.3
n
|> ceil() # → 11.0
|> IO.inspect
n
|> to_string() # → "10.3"
|> IO.inspect
https://hexdocs.pm/elixir/Float.html#content
TYPECASTING
Float.parse("34.1") # → {34.1, ""}
Integer.parse("34") # → {34, ""}
Float.to_string(34.1) # → "3.4100e+01"
Float.to_string(34.1, [decimals: 2, compact: true]) # → « 34.1 »
https://hexdocs.pm/elixir/Integer.html#parse/2
https://hexdocs.pm/elixir/Float.html#parse/1
https://hexdocs.pm/elixir/Integer.html#to_string/1
https://hexdocs.pm/elixir/Float.html#to_string/1
STRING
import String
str = "hello"
str |> length() # → 5
str |> slice(2..-1) # → "llo"
str |> split(" ") # → ["hello"]
str |> capitalize() # → "Hello"
str |> match(regex)
Elixir string are UTF-8 encoded binaries, we can concatenate
string like this :
"hello" <> " " <> "world" => "hello world"
https://hexdocs.pm/elixir/String.html
LIST&ENUM
list_mixed = [3.14, :pie, "Apple"]
list_integer = [5, 1, 2, 3]
list_integer
|> Enum.map(fn x -> 2 * x end)
|> IO.inspect # [10, 2, 4, 6]
|> Enum.concat([11, 9, 22, 23])
|> IO.inspect # [10, 2, 4, 6, 11, 9, 22, 23]
|> Enum.filter(fn x -> x > 10 end)
|> IO.inspect. # [11, 22, 23]
|> Enum.sort(fn (a,b) -> a > b end)
|> IO.inspect # [23, 22, 11]
https://hexdocs.pm/elixir/List.html#content
https://hexdocs.pm/elixir/Enum.html#content
STREAM
Enum problem : each enum should complete before piping
result to next enum.
Solution : use stream !
stream =(
1..3
|> Stream.map(fn x -> IO.inspect(x) end)
|> Stream.map(fn x -> x * 2 end)
|> Stream.map(fn x -> IO.inspect(x) end)
)
Enum.to_list(stream)
1
2
2
4
3
6
Each number is completely evaluated before moving to the
next number in the enumeration !
Streams are lazy !
Streams are useful when working with large, possibly
infinite, collections.
TUPLE
Tuple are like a statically-sized arrays : they hold a fixed
number of elements. For dynamic length use List.
list = [1, 2, true, 3]
tuple = {1, 2, true, 3}
gps_coordinate = {46.71109, 1.7191036}
{latitude, longitude} = {46.71109, 1.7191036} # pattern matching
https://hexdocs.pm/elixir/Tuple.html#functions
MAP(KEY/VALUE)
def get_gps_coordinates(country) do
%{
France: {46.71109, 1.7191036},
Spain: {40.2085, -3.713},
Italy: {41.29246, 12.5736108}
}[country]
end
When keys are dynamics :
map = %{"foo" => "bar", "hello" => "world"}
When keys are constants :
%{foo: "bar", hello: "world"} or %{:foo => "bar", :hello => "world"}
https://devhints.io/elixir#map
https://hexdocs.pm/elixir/Map.html#functions
STRUCT
defmodule ElixirPatternMatching.Country do
defstruct name: "", code: ""
end
defmodule ElixirPatternMatching.Examples do
alias ElixirPatternMatching.Country
def get_all_countries do
[
%Country{name: "France", code: "FR"},
%Country{name: "Spain", code: "ES"},
%Country{name: "Italy", code: "IT"}
]
end
end
https://elixir-lang.org/getting-started/structs.html
PATTERNMATCHING
TUPLE
{latitude, longitude} = {46.71109, 1.7191036} # tuple
{_latitude, longitude} = {46.71109, 1.7191036} # unused latitude
{_, longitude} = {46.71109, 1.7191036} # skip latitude
ARRAY
[first_item, second_item, third_item] = [
%{name: "France", code: "FR"},
%{name: "Spain", code: "ES"},
%{name: "Italy", code: "IT"}
] # destructuring
[first_element | rest] = [
%{name: "France", code: "FR"},
%{name: "Spain", code: "ES"},
%{name: "Italy", code: "IT"}
] # collect the rest into an array
[head | tail] = [
%{name: "France", code: "FR"},
%{name: "Spain", code: "ES"},
%{name: "Italy", code: "IT"}
] # tail is an array
[first_item, _, third_item] # skip the second item
[first_item, _second_item, third_item] # skip the second item
[first_element | _] # skip the rest
MAP
%{name: name, writer: writer, date: date} = %{
name: "Elixir In Action",
writer: "Sasa Juric",
date: "2019"
}
https://medium.com/@helabenkhalfallah/elixir-pattern-matching-
bd4a1eb4d59f
MULTICLAUSEFUNCTIONS
MULTICLAUSE
def get_cars(%{type: "bmw"} = params) do
IO.puts("I want only #{params.type} !")
end
def get_cars(%{type: "volkswagen"} = params) do
IO.puts("I want only #{params.type} !")
end
# the default clause
def get_cars(_) do
IO.puts("I want all cars !")
end
Instead of having classical branching (if/else), we can do
multiple clauses for our function get_cars.
MULTICLAUSEWITHGUARD
def get_cars(category, %Car{type: "bmw"} = car) when
is_binary(category) do
IO.puts("I want only #{String.upcase(car.type)}
#{String.upcase(car.category)} !")
end
def get_cars(%Car{} = car) do
IO.puts("I want all cars !")
end
https://medium.com/@helabenkhalfallah/elixir-pattern-matching-
bd4a1eb4d59f
IF,CASE,COND
IF
Multiple lignes :
if condition do
...
else
...
end
Example :
if String.contains?(name, " ") do
split_name = name |> String.split(" ")
first_letter = split_name |> List.first() |> String.slice(0, 1)
last_letter = split_name |> List.last() |> String.slice(0, 1)
else
name |> String.slice(0, 1)
end
Single ligne :
if condition, do: something, else: another_thing
Example :
def max(a, b) do
if a >= b, do: a, else: b
end
COND
Definition :
cond do
expression_1 ->
...
expression_2 ->
...
end
Example :
def greet(lang) do
cond do
lang == "en" ->
"Hello"
lang == "fr" ->
"Bonjour"
lang == "es" ->
"Hola"
true ->
"We don't have a greeting for that."
end
end
cond will raise an error if there is no match. To handle this,
we should define a condition set to true.
CASE
Definition :
case expression do
pattern_1 ->
...
pattern_2 ->
...
end
Example :
def greet(lang) do
case lang do
"eng" -> "Hello"
"fr" -> "Bonjour"
"es" -> "Hola"
_ -> "We don't have a greeting for that."
end
end
Default clause ‘_’ is mandatory.
ERRORHANDLING
TRY,RESCUE,AFTER
try do
opts
|> Keyword.fetch!(:source_file)
|> File.read!()
rescue
e in KeyError -> IO.puts("missing :source_file option")
e in File.Error -> IO.puts("unable to read source file")
end
TRY,CATCH
try do
...
catch
type_pattern_1, error_value_1 -> …
type_pattern_2, error_value_2 -> ...
end
THROW
try do
for x <- 0..10 do
if x == 5, do: throw(x)
IO.puts(x)
end
catch
x -> IO.puts("Caught: #{x}")
end
The throw function gives us the ability to exit execution
with a specific value we can catch and use.
CREATENEWEXCEPTION
defmodule ExampleError do
defexception message: "an example error has occurred"
end
try do
raise ExampleError
rescue
e in ExampleError -> e
end
IMPORT,ALIAS&USE
defmodule Stats do
alias Math.List, as: List
# In the remaining module definition List expands to
Math.List.
end
defmodule ElixirPatternMatching.Country do
defstruct name: "", code: ""
end
defmodule ElixirPatternMatching.Examples do
alias ElixirPatternMatching.Country
# we can call Country directly without
ElixirPatternMatching.Country
def get_all_countries do
[
%Country{name: "France", code: "FR"},
%Country{name: "Spain", code: "ES"},
%Country{name: "Italy", code: "IT"}
]
end
end
import Integer # import all Integer functions
import String
import List, only: [duplicate: 2] # import only duplicate
import ElixirPatternMatching.Examples,
only: [
get_gps_coordinates: 1,
get_all_countries: 0,
get_cars: 2
]
https://elixirschool.com/en/lessons/basics/modules/#composition
https://elixir-lang.org/getting-started/alias-require-and-import.html
3.
RUNTIME
BEAM&PROCESS
Erlang VM is called Beam.
Beam is a garbage collector memory management.
- inside Beam VM, process are lightweights and
independents (isolated).
- process are also independents from the Host'OS
(deterministic system, the same behavior everywhere).
- process communicate only by exchanging messages.
- each process has its own memory (a mailbox, a heap and a
stack) and a process control block (PCB) with information
about the process.
- each process has its own heap means that each process's
heap is garbage collected independently. Only one
process will be paused for GC and not the whole runtime,
this is unlike Java JVM which stop the world for GC.
- supervisor to supervise process healthiness (restart
process if needed).
- process can supervise each other.
- schedulers to balance execution.
MOREINFORMATIONS:
https://blog.stenmans.org/theBeamBook/#_what_is_a_process
https://blog.stenmans.org/theBeamBook/
#_the_erlang_virtual_machine_beam
http://erlang.org/faq/academic.html#idp33095056

More Related Content

What's hot

05 3.1 pak_tresc
05 3.1 pak_tresc05 3.1 pak_tresc
05 3.1 pak_tresc
Emotka
 
Securing k8s With Kubernetes Goat
Securing k8s With Kubernetes GoatSecuring k8s With Kubernetes Goat
Securing k8s With Kubernetes Goat
Muhammad Yuga Nugraha
 
Building Web Apps with WebAssembly and Blazor
Building Web Apps with WebAssembly and BlazorBuilding Web Apps with WebAssembly and Blazor
Building Web Apps with WebAssembly and Blazor
Amir Zuker
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)
iFour Technolab Pvt. Ltd.
 
OpenStack Glance
OpenStack GlanceOpenStack Glance
OpenStack Glance
openstackstl
 
Puppet - Configuration Management Made Eas(ier)
Puppet - Configuration Management Made Eas(ier)Puppet - Configuration Management Made Eas(ier)
Puppet - Configuration Management Made Eas(ier)
Aaron Bernstein
 
Taller: Exploración de redes con Nmap
Taller: Exploración de redes con NmapTaller: Exploración de redes con Nmap
Taller: Exploración de redes con Nmap
Websec México, S.C.
 
14
1414
.Net Core - not your daddy's dotnet
.Net Core - not your daddy's dotnet.Net Core - not your daddy's dotnet
.Net Core - not your daddy's dotnet
Rick van den Bosch
 
Open stack networking vlan, gre
Open stack networking   vlan, greOpen stack networking   vlan, gre
Open stack networking vlan, gre
Sim Janghoon
 
Mind control by amairullah khan lodhi
Mind control by amairullah khan lodhiMind control by amairullah khan lodhi
Mind control by amairullah khan lodhi
Amairullah Khan Lodhi
 
Express JS Middleware Tutorial
Express JS Middleware TutorialExpress JS Middleware Tutorial
Express JS Middleware Tutorial
Simplilearn
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
Ganesh Kondal
 
Dpdk performance
Dpdk performanceDpdk performance
Dpdk performance
Stephen Hemminger
 
Build a High Available NFS Cluster Based on CephFS - Shangzhong Zhu
Build a High Available NFS Cluster Based on CephFS - Shangzhong ZhuBuild a High Available NFS Cluster Based on CephFS - Shangzhong Zhu
Build a High Available NFS Cluster Based on CephFS - Shangzhong Zhu
Ceph Community
 
Linux kernel modules
Linux kernel modulesLinux kernel modules
Linux kernel modules
Dheryta Jaisinghani
 
Kubernetes in Docker
Kubernetes in DockerKubernetes in Docker
Kubernetes in Docker
Docker, Inc.
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
Saúl Ibarra Corretgé
 
도커없이 컨테이너 만들기 1편
도커없이 컨테이너 만들기 1편도커없이 컨테이너 만들기 1편
도커없이 컨테이너 만들기 1편
Sam Kim
 
WordPress vs Joomla vs Drupal
WordPress vs Joomla vs DrupalWordPress vs Joomla vs Drupal
WordPress vs Joomla vs Drupal
Avigma Technologies Private Limited
 

What's hot (20)

05 3.1 pak_tresc
05 3.1 pak_tresc05 3.1 pak_tresc
05 3.1 pak_tresc
 
Securing k8s With Kubernetes Goat
Securing k8s With Kubernetes GoatSecuring k8s With Kubernetes Goat
Securing k8s With Kubernetes Goat
 
Building Web Apps with WebAssembly and Blazor
Building Web Apps with WebAssembly and BlazorBuilding Web Apps with WebAssembly and Blazor
Building Web Apps with WebAssembly and Blazor
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)
 
OpenStack Glance
OpenStack GlanceOpenStack Glance
OpenStack Glance
 
Puppet - Configuration Management Made Eas(ier)
Puppet - Configuration Management Made Eas(ier)Puppet - Configuration Management Made Eas(ier)
Puppet - Configuration Management Made Eas(ier)
 
Taller: Exploración de redes con Nmap
Taller: Exploración de redes con NmapTaller: Exploración de redes con Nmap
Taller: Exploración de redes con Nmap
 
14
1414
14
 
.Net Core - not your daddy's dotnet
.Net Core - not your daddy's dotnet.Net Core - not your daddy's dotnet
.Net Core - not your daddy's dotnet
 
Open stack networking vlan, gre
Open stack networking   vlan, greOpen stack networking   vlan, gre
Open stack networking vlan, gre
 
Mind control by amairullah khan lodhi
Mind control by amairullah khan lodhiMind control by amairullah khan lodhi
Mind control by amairullah khan lodhi
 
Express JS Middleware Tutorial
Express JS Middleware TutorialExpress JS Middleware Tutorial
Express JS Middleware Tutorial
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Dpdk performance
Dpdk performanceDpdk performance
Dpdk performance
 
Build a High Available NFS Cluster Based on CephFS - Shangzhong Zhu
Build a High Available NFS Cluster Based on CephFS - Shangzhong ZhuBuild a High Available NFS Cluster Based on CephFS - Shangzhong Zhu
Build a High Available NFS Cluster Based on CephFS - Shangzhong Zhu
 
Linux kernel modules
Linux kernel modulesLinux kernel modules
Linux kernel modules
 
Kubernetes in Docker
Kubernetes in DockerKubernetes in Docker
Kubernetes in Docker
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
 
도커없이 컨테이너 만들기 1편
도커없이 컨테이너 만들기 1편도커없이 컨테이너 만들기 1편
도커없이 컨테이너 만들기 1편
 
WordPress vs Joomla vs Drupal
WordPress vs Joomla vs DrupalWordPress vs Joomla vs Drupal
WordPress vs Joomla vs Drupal
 

Similar to Elixir cheatsheet

Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
lachie
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
AbhishekSharma2958
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
Sudharsan S
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
Wes Oldenbeuving
 
Origins of Elixir programming language
Origins of Elixir programming languageOrigins of Elixir programming language
Origins of Elixir programming language
Pivorak MeetUp
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
Diacode
 
Elixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental ConceptsElixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental Concepts
Héla Ben Khalfallah
 
Introducing Elixir and OTP at the Erlang BASH
Introducing Elixir and OTP at the Erlang BASHIntroducing Elixir and OTP at the Erlang BASH
Introducing Elixir and OTP at the Erlang BASH
devbash
 
FPBrno 2018-05-22: Benchmarking in elixir
FPBrno 2018-05-22: Benchmarking in elixirFPBrno 2018-05-22: Benchmarking in elixir
FPBrno 2018-05-22: Benchmarking in elixir
Functional Programming Brno
 
10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language
Yaroslav Tkachenko
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
Svet Ivantchev
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
ConFoo
 
Ruby Intro {spection}
Ruby Intro {spection}Ruby Intro {spection}
Ruby Intro {spection}
Christian KAKESA
 
Phoenix for laravel developers
Phoenix for laravel developersPhoenix for laravel developers
Phoenix for laravel developers
Luiz Messias
 
Elixir introduction
Elixir introductionElixir introduction
Elixir introduction
Al Sayed Gamal
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
DroidConTLV
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ahmed Salama
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 

Similar to Elixir cheatsheet (20)

Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Origins of Elixir programming language
Origins of Elixir programming languageOrigins of Elixir programming language
Origins of Elixir programming language
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
 
Elixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental ConceptsElixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental Concepts
 
Introducing Elixir and OTP at the Erlang BASH
Introducing Elixir and OTP at the Erlang BASHIntroducing Elixir and OTP at the Erlang BASH
Introducing Elixir and OTP at the Erlang BASH
 
FPBrno 2018-05-22: Benchmarking in elixir
FPBrno 2018-05-22: Benchmarking in elixirFPBrno 2018-05-22: Benchmarking in elixir
FPBrno 2018-05-22: Benchmarking in elixir
 
10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 
Ruby Intro {spection}
Ruby Intro {spection}Ruby Intro {spection}
Ruby Intro {spection}
 
Phoenix for laravel developers
Phoenix for laravel developersPhoenix for laravel developers
Phoenix for laravel developers
 
Elixir introduction
Elixir introductionElixir introduction
Elixir introduction
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 

More from Héla Ben Khalfallah

DATABASE_DATA_STRUCTURE_DEVOXXFRANCE2024.pdf
DATABASE_DATA_STRUCTURE_DEVOXXFRANCE2024.pdfDATABASE_DATA_STRUCTURE_DEVOXXFRANCE2024.pdf
DATABASE_DATA_STRUCTURE_DEVOXXFRANCE2024.pdf
Héla Ben Khalfallah
 
CSS selectors
CSS selectorsCSS selectors
CSS selectors
Héla Ben Khalfallah
 
Yo messapp
Yo messappYo messapp
Elixir in a nutshell - Ecosystem (session 1)
Elixir in a nutshell - Ecosystem (session 1)Elixir in a nutshell - Ecosystem (session 1)
Elixir in a nutshell - Ecosystem (session 1)
Héla Ben Khalfallah
 
FP Using ES6+ (Cheat Sheet)
FP Using ES6+ (Cheat Sheet)FP Using ES6+ (Cheat Sheet)
FP Using ES6+ (Cheat Sheet)
Héla Ben Khalfallah
 
WONC DOVA
WONC DOVAWONC DOVA
Process & Methodologies (1.2)
Process & Methodologies (1.2)Process & Methodologies (1.2)
Process & Methodologies (1.2)
Héla Ben Khalfallah
 
Process & Methodologies (1.1)
Process & Methodologies (1.1)Process & Methodologies (1.1)
Process & Methodologies (1.1)
Héla Ben Khalfallah
 
Process & Methodologies (1.0)
Process & Methodologies (1.0)Process & Methodologies (1.0)
Process & Methodologies (1.0)
Héla Ben Khalfallah
 
La gestion en boucle fermée
La gestion en boucle ferméeLa gestion en boucle fermée
La gestion en boucle fermée
Héla Ben Khalfallah
 
Les règles de développement Angular
Les règles de développement AngularLes règles de développement Angular
Les règles de développement Angular
Héla Ben Khalfallah
 
Architecture ASIS (iOS)
Architecture ASIS (iOS)Architecture ASIS (iOS)
Architecture ASIS (iOS)
Héla Ben Khalfallah
 

More from Héla Ben Khalfallah (12)

DATABASE_DATA_STRUCTURE_DEVOXXFRANCE2024.pdf
DATABASE_DATA_STRUCTURE_DEVOXXFRANCE2024.pdfDATABASE_DATA_STRUCTURE_DEVOXXFRANCE2024.pdf
DATABASE_DATA_STRUCTURE_DEVOXXFRANCE2024.pdf
 
CSS selectors
CSS selectorsCSS selectors
CSS selectors
 
Yo messapp
Yo messappYo messapp
Yo messapp
 
Elixir in a nutshell - Ecosystem (session 1)
Elixir in a nutshell - Ecosystem (session 1)Elixir in a nutshell - Ecosystem (session 1)
Elixir in a nutshell - Ecosystem (session 1)
 
FP Using ES6+ (Cheat Sheet)
FP Using ES6+ (Cheat Sheet)FP Using ES6+ (Cheat Sheet)
FP Using ES6+ (Cheat Sheet)
 
WONC DOVA
WONC DOVAWONC DOVA
WONC DOVA
 
Process & Methodologies (1.2)
Process & Methodologies (1.2)Process & Methodologies (1.2)
Process & Methodologies (1.2)
 
Process & Methodologies (1.1)
Process & Methodologies (1.1)Process & Methodologies (1.1)
Process & Methodologies (1.1)
 
Process & Methodologies (1.0)
Process & Methodologies (1.0)Process & Methodologies (1.0)
Process & Methodologies (1.0)
 
La gestion en boucle fermée
La gestion en boucle ferméeLa gestion en boucle fermée
La gestion en boucle fermée
 
Les règles de développement Angular
Les règles de développement AngularLes règles de développement Angular
Les règles de développement Angular
 
Architecture ASIS (iOS)
Architecture ASIS (iOS)Architecture ASIS (iOS)
Architecture ASIS (iOS)
 

Recently uploaded

LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
lorraineandreiamcidl
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 

Recently uploaded (20)

LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 

Elixir cheatsheet

  • 2. 1. ECOSYSTEM Elixir is a dynamic & functional language. iex : Elixir's interactive shell. mix : build automation tool. hex : package manager for the Erlang ecosystem. COMMAND DESCRIPTION mix new my_project Create new project mix compile Compile project MIX_ENV=prod mix compile Compile by env Available envs: prod, dev & test (default is dev) iex -S mix + recompile Run project & reload on each change mix release Create release MIX_ENV=prod mix release Create release by env mix deps.get Add a dependency mix hex.outdated Show outdated dependencies mix hex.audit Audit dependencies mix do deps.get, deps.compile Multiple tasks
  • 3. DOCUMENTATION ExDoc: generate documentation mix docs https://hex.pm/packages/ex_doc Inch: documentation coverage mix inch https://github.com/rrrene/inch_ex CODEQUALITY ExUnit : unit test mix test Excoveralls : unit test coverage MIX_ENV=test mix coveralls https://github.com/parroty/excoveralls TAG DESCRIPTION @moduledoc Module documentation @doc Function documentation @spec @spec function_name (type1, type2) :: return_type Types spec documentation COMMAND DESCRIPTION mix format Code formatter credo & dialyxir mix credo --strict mix dialyzer Static code analysis
  • 4. 2. FUNDAMENTAL FILESEXTENSION NAMINGCONVENTION File snake_case Module UpperCamelCase Function snake_case Variable snake_case Unused parameter _foo Atoms snake_case or UpperCamelCase :true, :is_connected?, :debit_type_card .ex : elixir file .exs : elixir scripts file
  • 5. DEFINITION MODULE defmodule ElixirPatternMatching do // staff end FUNCTION def sum(x,y) do IO.inspect x IO.inspect y x + y # returned value end In Elixir, a function must be defined inside a module. PRIVATEFUNCTION defp get_gps_coordinates(country) do %{ France: {46.71109, 1.7191036}, Spain: {40.2085, -3.713}, Italy: {41.29246, 12.5736108} }[country] end
  • 6. PIPEOPERATOR "Elixir rocks" |> String.upcase() |> String.split() TYPECHECKS is_atom/1 is_bitstring/1 is_boolean/1 is_function/1 is_function/2 is_integer/1 is_float/1 is_binary/1 is_list/1 is_map/1 is_tuple/1 is_nil/1 is_number/1 is_pid/1 is_port/1 is_reference/1 https://hexdocs.pm/elixir/Kernel.html#is_atom/1
  • 7. INTEGEROPERATIONS import Integer n = 12 n |> digits() |> IO.inspect # → [1, 2] n |> to_charlist() |> IO.inspect # → '12' n |> to_string() |> IO.inspect # → "12" n |> is_even() |> IO.inspect # true n |> is_odd() |> IO.inspect # false https://hexdocs.pm/elixir/Integer.html#content
  • 8. FLOATOPERATIONS import Float n = 10.3 n |> ceil() # → 11.0 |> IO.inspect n |> to_string() # → "10.3" |> IO.inspect https://hexdocs.pm/elixir/Float.html#content TYPECASTING Float.parse("34.1") # → {34.1, ""} Integer.parse("34") # → {34, ""} Float.to_string(34.1) # → "3.4100e+01" Float.to_string(34.1, [decimals: 2, compact: true]) # → « 34.1 » https://hexdocs.pm/elixir/Integer.html#parse/2 https://hexdocs.pm/elixir/Float.html#parse/1 https://hexdocs.pm/elixir/Integer.html#to_string/1 https://hexdocs.pm/elixir/Float.html#to_string/1
  • 9. STRING import String str = "hello" str |> length() # → 5 str |> slice(2..-1) # → "llo" str |> split(" ") # → ["hello"] str |> capitalize() # → "Hello" str |> match(regex) Elixir string are UTF-8 encoded binaries, we can concatenate string like this : "hello" <> " " <> "world" => "hello world" https://hexdocs.pm/elixir/String.html LIST&ENUM list_mixed = [3.14, :pie, "Apple"] list_integer = [5, 1, 2, 3] list_integer |> Enum.map(fn x -> 2 * x end) |> IO.inspect # [10, 2, 4, 6] |> Enum.concat([11, 9, 22, 23]) |> IO.inspect # [10, 2, 4, 6, 11, 9, 22, 23] |> Enum.filter(fn x -> x > 10 end) |> IO.inspect. # [11, 22, 23] |> Enum.sort(fn (a,b) -> a > b end) |> IO.inspect # [23, 22, 11] https://hexdocs.pm/elixir/List.html#content https://hexdocs.pm/elixir/Enum.html#content
  • 10. STREAM Enum problem : each enum should complete before piping result to next enum. Solution : use stream ! stream =( 1..3 |> Stream.map(fn x -> IO.inspect(x) end) |> Stream.map(fn x -> x * 2 end) |> Stream.map(fn x -> IO.inspect(x) end) ) Enum.to_list(stream) 1 2 2 4 3 6 Each number is completely evaluated before moving to the next number in the enumeration ! Streams are lazy ! Streams are useful when working with large, possibly infinite, collections.
  • 11. TUPLE Tuple are like a statically-sized arrays : they hold a fixed number of elements. For dynamic length use List. list = [1, 2, true, 3] tuple = {1, 2, true, 3} gps_coordinate = {46.71109, 1.7191036} {latitude, longitude} = {46.71109, 1.7191036} # pattern matching https://hexdocs.pm/elixir/Tuple.html#functions MAP(KEY/VALUE) def get_gps_coordinates(country) do %{ France: {46.71109, 1.7191036}, Spain: {40.2085, -3.713}, Italy: {41.29246, 12.5736108} }[country] end When keys are dynamics : map = %{"foo" => "bar", "hello" => "world"} When keys are constants : %{foo: "bar", hello: "world"} or %{:foo => "bar", :hello => "world"} https://devhints.io/elixir#map https://hexdocs.pm/elixir/Map.html#functions
  • 12. STRUCT defmodule ElixirPatternMatching.Country do defstruct name: "", code: "" end defmodule ElixirPatternMatching.Examples do alias ElixirPatternMatching.Country def get_all_countries do [ %Country{name: "France", code: "FR"}, %Country{name: "Spain", code: "ES"}, %Country{name: "Italy", code: "IT"} ] end end https://elixir-lang.org/getting-started/structs.html PATTERNMATCHING TUPLE {latitude, longitude} = {46.71109, 1.7191036} # tuple {_latitude, longitude} = {46.71109, 1.7191036} # unused latitude {_, longitude} = {46.71109, 1.7191036} # skip latitude
  • 13. ARRAY [first_item, second_item, third_item] = [ %{name: "France", code: "FR"}, %{name: "Spain", code: "ES"}, %{name: "Italy", code: "IT"} ] # destructuring [first_element | rest] = [ %{name: "France", code: "FR"}, %{name: "Spain", code: "ES"}, %{name: "Italy", code: "IT"} ] # collect the rest into an array [head | tail] = [ %{name: "France", code: "FR"}, %{name: "Spain", code: "ES"}, %{name: "Italy", code: "IT"} ] # tail is an array [first_item, _, third_item] # skip the second item [first_item, _second_item, third_item] # skip the second item [first_element | _] # skip the rest MAP %{name: name, writer: writer, date: date} = %{ name: "Elixir In Action", writer: "Sasa Juric", date: "2019" } https://medium.com/@helabenkhalfallah/elixir-pattern-matching- bd4a1eb4d59f
  • 14. MULTICLAUSEFUNCTIONS MULTICLAUSE def get_cars(%{type: "bmw"} = params) do IO.puts("I want only #{params.type} !") end def get_cars(%{type: "volkswagen"} = params) do IO.puts("I want only #{params.type} !") end # the default clause def get_cars(_) do IO.puts("I want all cars !") end Instead of having classical branching (if/else), we can do multiple clauses for our function get_cars. MULTICLAUSEWITHGUARD def get_cars(category, %Car{type: "bmw"} = car) when is_binary(category) do IO.puts("I want only #{String.upcase(car.type)} #{String.upcase(car.category)} !") end def get_cars(%Car{} = car) do IO.puts("I want all cars !") end https://medium.com/@helabenkhalfallah/elixir-pattern-matching- bd4a1eb4d59f
  • 15. IF,CASE,COND IF Multiple lignes : if condition do ... else ... end Example : if String.contains?(name, " ") do split_name = name |> String.split(" ") first_letter = split_name |> List.first() |> String.slice(0, 1) last_letter = split_name |> List.last() |> String.slice(0, 1) else name |> String.slice(0, 1) end Single ligne : if condition, do: something, else: another_thing Example : def max(a, b) do if a >= b, do: a, else: b end
  • 16. COND Definition : cond do expression_1 -> ... expression_2 -> ... end Example : def greet(lang) do cond do lang == "en" -> "Hello" lang == "fr" -> "Bonjour" lang == "es" -> "Hola" true -> "We don't have a greeting for that." end end cond will raise an error if there is no match. To handle this, we should define a condition set to true.
  • 17. CASE Definition : case expression do pattern_1 -> ... pattern_2 -> ... end Example : def greet(lang) do case lang do "eng" -> "Hello" "fr" -> "Bonjour" "es" -> "Hola" _ -> "We don't have a greeting for that." end end Default clause ‘_’ is mandatory.
  • 18. ERRORHANDLING TRY,RESCUE,AFTER try do opts |> Keyword.fetch!(:source_file) |> File.read!() rescue e in KeyError -> IO.puts("missing :source_file option") e in File.Error -> IO.puts("unable to read source file") end TRY,CATCH try do ... catch type_pattern_1, error_value_1 -> … type_pattern_2, error_value_2 -> ... end
  • 19. THROW try do for x <- 0..10 do if x == 5, do: throw(x) IO.puts(x) end catch x -> IO.puts("Caught: #{x}") end The throw function gives us the ability to exit execution with a specific value we can catch and use. CREATENEWEXCEPTION defmodule ExampleError do defexception message: "an example error has occurred" end try do raise ExampleError rescue e in ExampleError -> e end
  • 20. IMPORT,ALIAS&USE defmodule Stats do alias Math.List, as: List # In the remaining module definition List expands to Math.List. end defmodule ElixirPatternMatching.Country do defstruct name: "", code: "" end defmodule ElixirPatternMatching.Examples do alias ElixirPatternMatching.Country # we can call Country directly without ElixirPatternMatching.Country def get_all_countries do [ %Country{name: "France", code: "FR"}, %Country{name: "Spain", code: "ES"}, %Country{name: "Italy", code: "IT"} ] end end
  • 21. import Integer # import all Integer functions import String import List, only: [duplicate: 2] # import only duplicate import ElixirPatternMatching.Examples, only: [ get_gps_coordinates: 1, get_all_countries: 0, get_cars: 2 ] https://elixirschool.com/en/lessons/basics/modules/#composition https://elixir-lang.org/getting-started/alias-require-and-import.html
  • 22. 3. RUNTIME BEAM&PROCESS Erlang VM is called Beam. Beam is a garbage collector memory management. - inside Beam VM, process are lightweights and independents (isolated). - process are also independents from the Host'OS (deterministic system, the same behavior everywhere). - process communicate only by exchanging messages. - each process has its own memory (a mailbox, a heap and a stack) and a process control block (PCB) with information about the process. - each process has its own heap means that each process's heap is garbage collected independently. Only one process will be paused for GC and not the whole runtime, this is unlike Java JVM which stop the world for GC. - supervisor to supervise process healthiness (restart process if needed). - process can supervise each other. - schedulers to balance execution.