SlideShare uma empresa Scribd logo
1 de 56
Baixar para ler offline
INTRODUCTION
TO ELIXIR
Madrid |> Elixir
29/03/2016
Offered by
RUBY ON RAILS SHOP
EMBRACING ELIXIR
About me:
Javier Cuevas
@javier_dev
P2P MARKETPLACE
FOR DOG OWNERS
About
Javier
Cuevas
Victor
Viruete
Ricardo
Garcia
Bruno
Bayón
Artur
Chruszc
WHAT IS
ELIXIR?
Elixir is a dynamic, functional language
designed for building scalable and
maintainable applications.
Elixir leverages the Erlang VM, known
for running low-latency, distributed and
fault-tolerant systems.
Created by José Valim circa 2012.
Former Rails Core Team member.
He was trying to make Rails really thread
safe but... ended up creating a new
programming language. Ops!
Elixir:
• Compiles to Erlang bytecode.
• It is not Ruby compiling to Erlang.
• Can call to any Erlang library with no performance
penalty.
• Enables developers’ productivity by offering
amazing tooling and beautiful documentation.
• WhatsApp
• Facebook (Chat backend)
• Amazon (SimpleDB)
• AdRoll
• Heroku
• Yahoo (Delicious)
• Ericsson (mobile networks)
• T-Mobile (SMS)
• World of Warcra!
• ....
Erlang is that ugly language from 1996 used in production
by some “small” guys such as:
2 million connections in a single node
WHY SHOULD I
CARE ABOUT
ELIXIR?
• CPUs today have gazillion of transistors (more than
ever), and a lot of cores.
• There is no way we can keep them busy by trying to
get them do all something at once.
• The only way to keep them busy is diving the work.
• In other words:
The future is functional and concurrent.
• Elixir proves that functional programming does not
need to be mathematical or complex.
• With Elixir we can do concurrency programming
without having to use abstractions such as locks or
semaphores.
How do we program without
GOTO state?
– Computer Science, 1968
How do we program without
mutable state?
– Computer Science, 2016
SHOW ME
THAT
ELIXIR
Value Types
• Integers
(arbitrary precision)
• Floats
0.12346
• Atoms (aka symbols)
:my_atom
true, false and nil are atoms
• Ranges
start..end
start & end can by any type
• Regular expresions
~r{regexp}
Collection Types
• Tuples (not arrays)
{:ok, 42, "next"}
• Linked Lists
(closest to arrays)
list = [1,2,3,4]
hd(list) # 1
tl(list) # [2, 3, 4]
• Binaries
<<1,2>>
Strings are UTF-8 encoded binaries.
• Maps
%{ key => value, key => value }
countries = %{"ES" => "Spain",
"Fr" => "France"}
countries["ES"] # Spain
System Types
• PIDs:
Reference to local or remote process.
A new PID is created when you spawn a new
process
• Ports:
Reference to a port ^_^
Anonymous Functions
• AKA unnamed functions.
• Can be passed as arguments (they’re also a type)
• Parenthesis are optional.
iex> add = fn (a, b) -> a + b end
#Function<12.71889879/2 in :erl_eval.expr/5>
iex> add.(1, 2)
3 that dot before parenthesis is only for calling anonymous functions
Named Functions
defmodule MyModule do
def say_hello(name) do
IO.puts “Hello #{name}”
end
end
iex> MyModule.say_hello("Madrid Elixir")
Hello Madrid Elixir
Pattern Matching
• In Elixir: a = 1
does not mean we are assigning 1 to the variable a.
• The equal signs means we are asserting that the le! hand side
(LHS) is equal to the right one (RHS).
It’s like basic algebra.
iex> a = 1
1
iex> 1 = a
1
you can’t do that in non functional languages
Pattern Matching
• Instead of assigning a variable, in Elixir we talk about
binding a variable.
• In contrasts to Erlang, Elixir does allow rebinding a
variable.
iex> a = 1
1
iex> a = 2
2
Pattern Matching
Let’s do some magic:
iex> [1, a, 3] = [1, 2, 3]
[1, 2, 3]
iex> a
2
Pattern Matching
You can ignore values with “_”
iex> [a, _, _] = [1, 2, 3]
[1, 2, 3]
iex> a
1
Pattern Matching
You can reuse the previous bind value with
the pin operator “^”
iex> a = 1
1
iex> [^a, 2, 3 ] = [ 1, 2, 3 ]
[1, 2, 3]
Pattern Matching &
Function Signatures
Function signatures use pattern matching.
Therefore we can have more than one signature.
defmodule Factorial do
def of(0), do: 1
def of(x), do: x * of(x-1)
end
look mum! programing without if - else
Guards
When pattern matching is not sufficient to select the
signature to use, we can use guards.
defmodule Factorial
do def of(0), do: 1
def of(n) when n > 0 do
n * of(n-1)
end
end
Guards
defmodule MyModule do
def what_is(x) when is_number(x) do
IO.puts "#{x} is a number”
end
def what_is(x) when is_list(x) do
IO.puts "#{inspect(x)} is a list"
end
end
MyModule.what_is(99) # => 99 is a number
MyModule.what_is([1,2,3]) # => [1,2,3] is a list
you can use guards with “case” too
Macros
• Macros enable to extend the language and to create
DSLs (domain specific languages), in order to remove
boilerplate and make code more readable.
• You won’t probably create new macros unless you’re
writing a library. They should be written responsible.
Macros
• Did you know that Erlang has no “if” (as the one we
have in OOP languages)?
• Elixir does have “if”, “else” and even “unless” (because
Mr. Valim is a kind person), however it is actually a
macro.
• These 3 macros rely on “case” which... (surprise!) it uses
Pattern Matching.
Macros
http://elixir-lang.org/docs/stable/elixir/Kernel.html#if
Macros
Another cool example for a DSL created with
Macros is ExUnit, the test library that comes
with Elixir:
defmodule MathTest do
use ExUnit.Case
test "basic operations" do
assert 1 + 1 == 2
end
end
macro! macro! macro!
Exceptions?
No! Pattern Matching!
case File.open("chain.exs") do
{ :ok, file } -> # something
{ :error, reason } -> # uh oh
end
Pipe Operator |>
Typical code in OOP / imperative programming:
people = DB.find_customers
orders = Orders.for_customers(people)
tax = sales_tax(orders, 2013)
filing = prepare_filing(tax)
We could rewrite it as...
filing = prepare_filing(
sales_tax(Orders.for_customers(
DB.find_customers), 2013))
Pipe Operator |>
With Elixir pipe operator we can do just
filing = DB.find_customers
|> Orders.for_customers
|> sales_tax(2013)
|> prepare_filing
“|>” passes the result from the le! expression as the
first argument to the right expression. Kinda like the
Unix pipe “|”. It’s just useful syntax sugar.
Mix
• Mix is a build tool that ships with Elixir that provides
tasks for creating, compiling, testing your application,
managing its dependencies and much more.
• Kind of like rake (Ruby) on steroids.
Mix
➜ ~ mix --help
mix # Runs the default task (current: "mix
run")
mix app.start # Starts all registered apps
mix archive # Lists all archives
mix archive.build # Archives this project into a .ez file
mix archive.install # Installs an archive locally
mix archive.uninstall # Uninstalls archives
mix clean # Deletes generated application files
mix cmd # Executes the given command
mix compile # Compiles source files
mix deps # Lists dependencies and their status
mix deps.clean # Deletes the given dependencies' files
mix deps.compile # Compiles dependencies
mix deps.get # Gets all out of date dependencies
mix deps.unlock # Unlocks the given dependencies
mix deps.update # Updates the given dependencies
mix do # Executes the tasks separated by comma
mix escript.build # Builds an escript for the project
mix help # Prints help information for tasks
mix hex # Prints Hex help information
mix hex.build # Builds a new package version locally
mix hex.config # Reads or updates Hex config
mix hex.docs # Publishes docs for package
mix hex.info # Prints Hex information
mix hex.key # Hex API key tasks
mix hex.outdated # Shows outdated Hex deps for the
current project
mix hex.owner # Hex package ownership tasks
mix hex.public_keys # Manages Hex public keys
mix hex.publish # Publishes a new package version
mix hex.registry # Hex registry tasks
mix hex.search # Searches for package names
mix hex.user # Hex user tasks
mix loadconfig # Loads and persists the given
configuration
mix local # Lists local tasks
mix local.hex # Installs Hex locally
mix local.phoenix # Updates Phoenix locally
mix local.public_keys # Manages public keys
mix local.rebar # Installs rebar locally
mix new # Creates a new Elixir project
mix phoenix.new # Creates a new Phoenix v1.1.4
application
mix profile.fprof # Profiles the given file or expression
with fprof
mix run # Runs the given file or expression
mix test # Runs a project's tests
iex -S mix # Starts IEx and run the default task
Mixfile
defmodule MyCoolProject.Mixfile do
use Mix.Project
def project do
[ app: :my_cool_projet,
version: "0.0.1",
deps: deps ]
end
# Configuration for the OTP application
def application do
[mod: { MyCoolProject, [] }]
end
# Returns the list of dependencies in the format:
# { :foobar, git: "https://github.com/elixir-lang/foobar.git", tag: "0.1" }
#
# To specify particular versions, regardless of the tag, do:
# { :barbat, "~> 0.1", github: "elixir-lang/barbat" }
defp deps do
[
{:exactor, github: "sasa1977/exactor"},
{:"erlang-serial", github: "knewter/erlang-serial", app: false}
]
end
end
DocTests
defmodule MyModule do
@doc ~S"""
Sums two numbers
## Examples
iex> MyModule.sum(1, 2)
3
"""
def sum(a, b) do
a + b
end
end
$ mix test
Compiled lib/my_module.ex
..
Finished in 0.1 seconds (0.1s on
load, 0.00s on tests)
2 tests, 0 failures
Randomized with seed 307356
OTP
• OTP stands for Open Telecom Platform, but the name is
misleading. OTP is not only for telecom related so!ware.
• It’s a bundle that includes a large number of libraries to
solve problems like state management, application
discovery, failure detection, hot code swapping, and server
structure .
• Unfortunately, we don’t have time to talk about OTP today :/
Erlang Observer
iex> :observer.start
ELIXIR FOR
WEB APPS
Phoenix Framework
• MVC web framework created by Chris McCord. José
Valim is working on it too.
• Tastes a little bit like Ruby on Rails, but it is not.
• Aims for high developer productivity and high
application performance.
• It has powerful abstractions for creating modern web
apps in 2016, such as Channels (~ web sockets).
Phoenix Framework
• Create a new project
$ mix phoenix.new hello_phoenix
• Create database
$ mix ecto.create
• Run server
$ mix phoenix.server
Phoenix Framework
• It’s actually the top layer of a multi-layer system
designed to be modular and flexible.
• The other layers include Plug (kind of like Ruby’s Rack),
Ecto (kind of like ActiveRecord), and Cowboy, the Erlang
HTTP server.
Phoenix Framework
• Thanks to the power of Elixir and the ease of use of
Channels in Phoenix we can create web apps where we
have 1 real time bi-directional data channel with every
user (a websocket). And it scales, for real.
• Despite that WebSockets are the main transport for
Phoenix’s channels, it also supports other transport
mechanism for old browsers or embedded devices.
Phoenix Framework
• It plays nicely with the modern front-end world (ES6) by
relying on Brunch, a fast and simple asset build tool.
• It’s very easy to replace Brunch by Webpack or any other
hipster build tool of your choice.
• Note that Brunch requires Node.js (trollface).
Phoenix Framework
https://www.youtube.com/watch?v=3LiLjVCDEpU
Phoenix Framework
Phoenix Framework
HOW FAST
IS ELIXIR?
spoiler... a lot!
http://bob.ippoli.to/haskell-for-erlangers-2014/#/cost-of-concurrency
SHOWCASE
Showcase
• BSRBulb: Elixir library to control a Bluetooth Smart Bulb.
https://github.com/diacode/bsr_bulb
• Phoenix Trello: a Trello tribute with Phoenix & React.
https://github.com/bigardone/phoenix-trello
https://blog.diacode.com/trello-clone-with-phoenix-and-react-pt-1
• Phoenix Toggl: a Toggl tribute with Phoenix & React.
https://github.com/bigardone/phoenix-toggl
• Elixir Toggl API Wrapper
https://github.com/diacode/togglex
WHERE TO
GO FROM
HERE?
Next steps
• Watch every talk by José Valim. Really, you won’t regret.
• Books:
Programming Elixir – Dave Thomas
Programming Phoenix – Chris McCord, Bruce Tate & José Valim.
• Elixir Getting Started Guide (really good!)
http://elixir-lang.org/getting-started/introduction.html
• Phoenix Guide (really good!)
http://www.phoenixframework.org/docs/overview
• Elixir Radar
http://plataformatec.com.br/elixir-radar
• Madrid |> Elixir Slack (#madrid-meetup)
https://elixir-slackin.herokuapp.com/
THANK YOU
Questions?

Mais conteúdo relacionado

Mais procurados

Introduction to Docker - 2017
Introduction to Docker - 2017Introduction to Docker - 2017
Introduction to Docker - 2017Docker, Inc.
 
SRE-iously! Reliability!
SRE-iously! Reliability!SRE-iously! Reliability!
SRE-iously! Reliability!New Relic
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | EdurekaEdureka!
 
Docker 101: Introduction to Docker
Docker 101: Introduction to DockerDocker 101: Introduction to Docker
Docker 101: Introduction to DockerDocker, Inc.
 
Intro to elixir and phoenix
Intro to elixir and phoenixIntro to elixir and phoenix
Intro to elixir and phoenixJared Smith
 
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...Edureka!
 
Docker Commands With Examples | Docker Tutorial | DevOps Tutorial | Docker Tr...
Docker Commands With Examples | Docker Tutorial | DevOps Tutorial | Docker Tr...Docker Commands With Examples | Docker Tutorial | DevOps Tutorial | Docker Tr...
Docker Commands With Examples | Docker Tutorial | DevOps Tutorial | Docker Tr...Edureka!
 
Flow-based programming with Elixir
Flow-based programming with ElixirFlow-based programming with Elixir
Flow-based programming with ElixirAnton Mishchuk
 
What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...
What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...
What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...Edureka!
 
Continuous Delivery with Jenkins
Continuous Delivery with JenkinsContinuous Delivery with Jenkins
Continuous Delivery with JenkinsJadson Santos
 
Présentation docker et kubernetes
Présentation docker et kubernetesPrésentation docker et kubernetes
Présentation docker et kubernetesKiwi Backup
 
What Is Docker? | What Is Docker And How It Works? | Docker Tutorial For Begi...
What Is Docker? | What Is Docker And How It Works? | Docker Tutorial For Begi...What Is Docker? | What Is Docker And How It Works? | Docker Tutorial For Begi...
What Is Docker? | What Is Docker And How It Works? | Docker Tutorial For Begi...Simplilearn
 
Docker 101 : Introduction to Docker and Containers
Docker 101 : Introduction to Docker and ContainersDocker 101 : Introduction to Docker and Containers
Docker 101 : Introduction to Docker and ContainersYajushi Srivastava
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Ansible Tutorial.pdf
Ansible Tutorial.pdfAnsible Tutorial.pdf
Ansible Tutorial.pdfNigussMehari4
 

Mais procurados (20)

Introduction to Docker - 2017
Introduction to Docker - 2017Introduction to Docker - 2017
Introduction to Docker - 2017
 
SRE-iously! Reliability!
SRE-iously! Reliability!SRE-iously! Reliability!
SRE-iously! Reliability!
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
 
Docker 101: Introduction to Docker
Docker 101: Introduction to DockerDocker 101: Introduction to Docker
Docker 101: Introduction to Docker
 
Intro to elixir and phoenix
Intro to elixir and phoenixIntro to elixir and phoenix
Intro to elixir and phoenix
 
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
 
Intro to Terraform
Intro to TerraformIntro to Terraform
Intro to Terraform
 
Docker Commands With Examples | Docker Tutorial | DevOps Tutorial | Docker Tr...
Docker Commands With Examples | Docker Tutorial | DevOps Tutorial | Docker Tr...Docker Commands With Examples | Docker Tutorial | DevOps Tutorial | Docker Tr...
Docker Commands With Examples | Docker Tutorial | DevOps Tutorial | Docker Tr...
 
Flow-based programming with Elixir
Flow-based programming with ElixirFlow-based programming with Elixir
Flow-based programming with Elixir
 
What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...
What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...
What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...
 
Continuous Delivery with Jenkins
Continuous Delivery with JenkinsContinuous Delivery with Jenkins
Continuous Delivery with Jenkins
 
Docker Introduction
Docker IntroductionDocker Introduction
Docker Introduction
 
Présentation docker et kubernetes
Présentation docker et kubernetesPrésentation docker et kubernetes
Présentation docker et kubernetes
 
Docker Kubernetes Istio
Docker Kubernetes IstioDocker Kubernetes Istio
Docker Kubernetes Istio
 
What Is Docker? | What Is Docker And How It Works? | Docker Tutorial For Begi...
What Is Docker? | What Is Docker And How It Works? | Docker Tutorial For Begi...What Is Docker? | What Is Docker And How It Works? | Docker Tutorial For Begi...
What Is Docker? | What Is Docker And How It Works? | Docker Tutorial For Begi...
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
 
Docker 101 : Introduction to Docker and Containers
Docker 101 : Introduction to Docker and ContainersDocker 101 : Introduction to Docker and Containers
Docker 101 : Introduction to Docker and Containers
 
gRPC in Go
gRPC in GogRPC in Go
gRPC in Go
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Ansible Tutorial.pdf
Ansible Tutorial.pdfAnsible Tutorial.pdf
Ansible Tutorial.pdf
 

Destaque

7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOS7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOSJorge Ortiz
 
Emoticritico: midiendo las emociones de los políticos
Emoticritico: midiendo las emociones de los políticosEmoticritico: midiendo las emociones de los políticos
Emoticritico: midiendo las emociones de los políticosIsrael Gutiérrez
 
Aceleradoras de startups educativas
Aceleradoras de startups educativasAceleradoras de startups educativas
Aceleradoras de startups educativasAurelio Jimenez
 
Make startup development great again!
Make startup development great again!Make startup development great again!
Make startup development great again!Israel Gutiérrez
 
Hello elixir (and otp)
Hello elixir (and otp)Hello elixir (and otp)
Hello elixir (and otp)Abel Muíño
 
Elixir Into Production
Elixir Into ProductionElixir Into Production
Elixir Into ProductionJamie Winsor
 
How Elixir helped us scale our Video User Profile Service for the Olympics
How Elixir helped us scale our Video User Profile Service for the OlympicsHow Elixir helped us scale our Video User Profile Service for the Olympics
How Elixir helped us scale our Video User Profile Service for the OlympicsEmerson Macedo
 
Elixir – Peeking into Elixir's Processes, OTP and Supervisors
Elixir – Peeking into Elixir's Processes, OTP and SupervisorsElixir – Peeking into Elixir's Processes, OTP and Supervisors
Elixir – Peeking into Elixir's Processes, OTP and SupervisorsBenjamin Tan
 
Learn Elixir at Manchester Lambda Lounge
Learn Elixir at Manchester Lambda LoungeLearn Elixir at Manchester Lambda Lounge
Learn Elixir at Manchester Lambda LoungeChi-chi Ekweozor
 
Syrup,elixir,spirits
Syrup,elixir,spiritsSyrup,elixir,spirits
Syrup,elixir,spiritsarjun kaushik
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails DevsDiacode
 
Erlang e Elixir por uma web mais feliz
Erlang e Elixir por uma web mais felizErlang e Elixir por uma web mais feliz
Erlang e Elixir por uma web mais felizBruno Henrique - Garu
 
Functional Programming with Ruby
Functional Programming with RubyFunctional Programming with Ruby
Functional Programming with Rubytokland
 
ELIXIR Node poster Denmark
ELIXIR Node poster DenmarkELIXIR Node poster Denmark
ELIXIR Node poster DenmarkELIXIR-Europe
 

Destaque (20)

7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOS7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOS
 
Emoticritico: midiendo las emociones de los políticos
Emoticritico: midiendo las emociones de los políticosEmoticritico: midiendo las emociones de los políticos
Emoticritico: midiendo las emociones de los políticos
 
Aceleradoras de startups educativas
Aceleradoras de startups educativasAceleradoras de startups educativas
Aceleradoras de startups educativas
 
Make startup development great again!
Make startup development great again!Make startup development great again!
Make startup development great again!
 
Elixirs
ElixirsElixirs
Elixirs
 
Hello elixir (and otp)
Hello elixir (and otp)Hello elixir (and otp)
Hello elixir (and otp)
 
Elixir intro
Elixir introElixir intro
Elixir intro
 
Elixir Into Production
Elixir Into ProductionElixir Into Production
Elixir Into Production
 
Elixir
ElixirElixir
Elixir
 
How Elixir helped us scale our Video User Profile Service for the Olympics
How Elixir helped us scale our Video User Profile Service for the OlympicsHow Elixir helped us scale our Video User Profile Service for the Olympics
How Elixir helped us scale our Video User Profile Service for the Olympics
 
Elixir basics-2
Elixir basics-2Elixir basics-2
Elixir basics-2
 
Elixir – Peeking into Elixir's Processes, OTP and Supervisors
Elixir – Peeking into Elixir's Processes, OTP and SupervisorsElixir – Peeking into Elixir's Processes, OTP and Supervisors
Elixir – Peeking into Elixir's Processes, OTP and Supervisors
 
Learn Elixir at Manchester Lambda Lounge
Learn Elixir at Manchester Lambda LoungeLearn Elixir at Manchester Lambda Lounge
Learn Elixir at Manchester Lambda Lounge
 
The Magic Of Elixir
The Magic Of ElixirThe Magic Of Elixir
The Magic Of Elixir
 
Syrup,elixir,spirits
Syrup,elixir,spiritsSyrup,elixir,spirits
Syrup,elixir,spirits
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails Devs
 
Erlang e Elixir por uma web mais feliz
Erlang e Elixir por uma web mais felizErlang e Elixir por uma web mais feliz
Erlang e Elixir por uma web mais feliz
 
Erlang and Elixir
Erlang and ElixirErlang and Elixir
Erlang and Elixir
 
Functional Programming with Ruby
Functional Programming with RubyFunctional Programming with Ruby
Functional Programming with Ruby
 
ELIXIR Node poster Denmark
ELIXIR Node poster DenmarkELIXIR Node poster Denmark
ELIXIR Node poster Denmark
 

Semelhante a Introduction to Elixir

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 BASHdevbash
 
Echtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQLEchtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQLMoritz Flucht
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manualSami Said
 
Kostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program DevelopmenKostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program DevelopmenKonstantin Sorokin
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain艾鍗科技
 
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
 
Intro to React
Intro to ReactIntro to React
Intro to ReactTroy Miles
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best PracticesDavid Keener
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixirbrien_wankel
 

Semelhante a Introduction to Elixir (20)

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
 
Elixir
ElixirElixir
Elixir
 
Echtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQLEchtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQL
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
Bioinformatics v2014 wim_vancriekinge
Bioinformatics v2014 wim_vancriekingeBioinformatics v2014 wim_vancriekinge
Bioinformatics v2014 wim_vancriekinge
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
Kostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program DevelopmenKostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program Developmen
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Eclipse meets e4
Eclipse meets e4Eclipse meets e4
Eclipse meets e4
 
嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain
 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
 
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...
 
Intro to Elixir talk
Intro to Elixir talkIntro to Elixir talk
Intro to Elixir talk
 
Elixir
ElixirElixir
Elixir
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Elixir introduction
Elixir introductionElixir introduction
Elixir introduction
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
 

Mais de Diacode

CI/CD with Kubernetes, Helm & Wercker (#madScalability)
CI/CD with Kubernetes, Helm & Wercker (#madScalability)CI/CD with Kubernetes, Helm & Wercker (#madScalability)
CI/CD with Kubernetes, Helm & Wercker (#madScalability)Diacode
 
Startup nomads
Startup nomadsStartup nomads
Startup nomadsDiacode
 
Ruby on Rails & TDD con RSpec
Ruby on Rails & TDD con RSpecRuby on Rails & TDD con RSpec
Ruby on Rails & TDD con RSpecDiacode
 
Hacking your bank with Ruby and reverse engineering (Madrid.rb)
Hacking your bank with Ruby and reverse engineering (Madrid.rb)Hacking your bank with Ruby and reverse engineering (Madrid.rb)
Hacking your bank with Ruby and reverse engineering (Madrid.rb)Diacode
 
TLKR.io @ Betabeers Madrid
TLKR.io @ Betabeers MadridTLKR.io @ Betabeers Madrid
TLKR.io @ Betabeers MadridDiacode
 
Métricas para hacer crecer tu proyecto
Métricas para hacer crecer tu proyectoMétricas para hacer crecer tu proyecto
Métricas para hacer crecer tu proyectoDiacode
 
Métricas para hacer crecer tu proyecto
Métricas para hacer crecer tu proyectoMétricas para hacer crecer tu proyecto
Métricas para hacer crecer tu proyectoDiacode
 
Presentación de Kogi
Presentación de KogiPresentación de Kogi
Presentación de KogiDiacode
 
Educación: The Next Big Thing
Educación: The Next Big ThingEducación: The Next Big Thing
Educación: The Next Big ThingDiacode
 
Front-End Frameworks: a quick overview
Front-End Frameworks: a quick overviewFront-End Frameworks: a quick overview
Front-End Frameworks: a quick overviewDiacode
 
Taller de Introducción a Ruby on Rails (2ª parte)
Taller de Introducción a Ruby on Rails (2ª parte)Taller de Introducción a Ruby on Rails (2ª parte)
Taller de Introducción a Ruby on Rails (2ª parte)Diacode
 
Taller de Introducción a Ruby on Rails
Taller de Introducción a Ruby on RailsTaller de Introducción a Ruby on Rails
Taller de Introducción a Ruby on RailsDiacode
 

Mais de Diacode (12)

CI/CD with Kubernetes, Helm & Wercker (#madScalability)
CI/CD with Kubernetes, Helm & Wercker (#madScalability)CI/CD with Kubernetes, Helm & Wercker (#madScalability)
CI/CD with Kubernetes, Helm & Wercker (#madScalability)
 
Startup nomads
Startup nomadsStartup nomads
Startup nomads
 
Ruby on Rails & TDD con RSpec
Ruby on Rails & TDD con RSpecRuby on Rails & TDD con RSpec
Ruby on Rails & TDD con RSpec
 
Hacking your bank with Ruby and reverse engineering (Madrid.rb)
Hacking your bank with Ruby and reverse engineering (Madrid.rb)Hacking your bank with Ruby and reverse engineering (Madrid.rb)
Hacking your bank with Ruby and reverse engineering (Madrid.rb)
 
TLKR.io @ Betabeers Madrid
TLKR.io @ Betabeers MadridTLKR.io @ Betabeers Madrid
TLKR.io @ Betabeers Madrid
 
Métricas para hacer crecer tu proyecto
Métricas para hacer crecer tu proyectoMétricas para hacer crecer tu proyecto
Métricas para hacer crecer tu proyecto
 
Métricas para hacer crecer tu proyecto
Métricas para hacer crecer tu proyectoMétricas para hacer crecer tu proyecto
Métricas para hacer crecer tu proyecto
 
Presentación de Kogi
Presentación de KogiPresentación de Kogi
Presentación de Kogi
 
Educación: The Next Big Thing
Educación: The Next Big ThingEducación: The Next Big Thing
Educación: The Next Big Thing
 
Front-End Frameworks: a quick overview
Front-End Frameworks: a quick overviewFront-End Frameworks: a quick overview
Front-End Frameworks: a quick overview
 
Taller de Introducción a Ruby on Rails (2ª parte)
Taller de Introducción a Ruby on Rails (2ª parte)Taller de Introducción a Ruby on Rails (2ª parte)
Taller de Introducción a Ruby on Rails (2ª parte)
 
Taller de Introducción a Ruby on Rails
Taller de Introducción a Ruby on RailsTaller de Introducción a Ruby on Rails
Taller de Introducción a Ruby on Rails
 

Último

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 

Último (20)

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 

Introduction to Elixir

  • 1. INTRODUCTION TO ELIXIR Madrid |> Elixir 29/03/2016 Offered by
  • 2. RUBY ON RAILS SHOP EMBRACING ELIXIR About me: Javier Cuevas @javier_dev P2P MARKETPLACE FOR DOG OWNERS
  • 5. Elixir is a dynamic, functional language designed for building scalable and maintainable applications. Elixir leverages the Erlang VM, known for running low-latency, distributed and fault-tolerant systems.
  • 6. Created by José Valim circa 2012. Former Rails Core Team member. He was trying to make Rails really thread safe but... ended up creating a new programming language. Ops!
  • 7. Elixir: • Compiles to Erlang bytecode. • It is not Ruby compiling to Erlang. • Can call to any Erlang library with no performance penalty. • Enables developers’ productivity by offering amazing tooling and beautiful documentation.
  • 8. • WhatsApp • Facebook (Chat backend) • Amazon (SimpleDB) • AdRoll • Heroku • Yahoo (Delicious) • Ericsson (mobile networks) • T-Mobile (SMS) • World of Warcra! • .... Erlang is that ugly language from 1996 used in production by some “small” guys such as: 2 million connections in a single node
  • 9. WHY SHOULD I CARE ABOUT ELIXIR?
  • 10. • CPUs today have gazillion of transistors (more than ever), and a lot of cores. • There is no way we can keep them busy by trying to get them do all something at once. • The only way to keep them busy is diving the work. • In other words: The future is functional and concurrent.
  • 11. • Elixir proves that functional programming does not need to be mathematical or complex. • With Elixir we can do concurrency programming without having to use abstractions such as locks or semaphores.
  • 12. How do we program without GOTO state? – Computer Science, 1968 How do we program without mutable state? – Computer Science, 2016
  • 14. Value Types • Integers (arbitrary precision) • Floats 0.12346 • Atoms (aka symbols) :my_atom true, false and nil are atoms • Ranges start..end start & end can by any type • Regular expresions ~r{regexp}
  • 15. Collection Types • Tuples (not arrays) {:ok, 42, "next"} • Linked Lists (closest to arrays) list = [1,2,3,4] hd(list) # 1 tl(list) # [2, 3, 4] • Binaries <<1,2>> Strings are UTF-8 encoded binaries. • Maps %{ key => value, key => value } countries = %{"ES" => "Spain", "Fr" => "France"} countries["ES"] # Spain
  • 16. System Types • PIDs: Reference to local or remote process. A new PID is created when you spawn a new process • Ports: Reference to a port ^_^
  • 17. Anonymous Functions • AKA unnamed functions. • Can be passed as arguments (they’re also a type) • Parenthesis are optional. iex> add = fn (a, b) -> a + b end #Function<12.71889879/2 in :erl_eval.expr/5> iex> add.(1, 2) 3 that dot before parenthesis is only for calling anonymous functions
  • 18. Named Functions defmodule MyModule do def say_hello(name) do IO.puts “Hello #{name}” end end iex> MyModule.say_hello("Madrid Elixir") Hello Madrid Elixir
  • 19. Pattern Matching • In Elixir: a = 1 does not mean we are assigning 1 to the variable a. • The equal signs means we are asserting that the le! hand side (LHS) is equal to the right one (RHS). It’s like basic algebra. iex> a = 1 1 iex> 1 = a 1 you can’t do that in non functional languages
  • 20. Pattern Matching • Instead of assigning a variable, in Elixir we talk about binding a variable. • In contrasts to Erlang, Elixir does allow rebinding a variable. iex> a = 1 1 iex> a = 2 2
  • 21. Pattern Matching Let’s do some magic: iex> [1, a, 3] = [1, 2, 3] [1, 2, 3] iex> a 2
  • 22. Pattern Matching You can ignore values with “_” iex> [a, _, _] = [1, 2, 3] [1, 2, 3] iex> a 1
  • 23. Pattern Matching You can reuse the previous bind value with the pin operator “^” iex> a = 1 1 iex> [^a, 2, 3 ] = [ 1, 2, 3 ] [1, 2, 3]
  • 24. Pattern Matching & Function Signatures Function signatures use pattern matching. Therefore we can have more than one signature. defmodule Factorial do def of(0), do: 1 def of(x), do: x * of(x-1) end look mum! programing without if - else
  • 25. Guards When pattern matching is not sufficient to select the signature to use, we can use guards. defmodule Factorial do def of(0), do: 1 def of(n) when n > 0 do n * of(n-1) end end
  • 26. Guards defmodule MyModule do def what_is(x) when is_number(x) do IO.puts "#{x} is a number” end def what_is(x) when is_list(x) do IO.puts "#{inspect(x)} is a list" end end MyModule.what_is(99) # => 99 is a number MyModule.what_is([1,2,3]) # => [1,2,3] is a list you can use guards with “case” too
  • 27. Macros • Macros enable to extend the language and to create DSLs (domain specific languages), in order to remove boilerplate and make code more readable. • You won’t probably create new macros unless you’re writing a library. They should be written responsible.
  • 28. Macros • Did you know that Erlang has no “if” (as the one we have in OOP languages)? • Elixir does have “if”, “else” and even “unless” (because Mr. Valim is a kind person), however it is actually a macro. • These 3 macros rely on “case” which... (surprise!) it uses Pattern Matching.
  • 30. Macros Another cool example for a DSL created with Macros is ExUnit, the test library that comes with Elixir: defmodule MathTest do use ExUnit.Case test "basic operations" do assert 1 + 1 == 2 end end macro! macro! macro!
  • 31. Exceptions? No! Pattern Matching! case File.open("chain.exs") do { :ok, file } -> # something { :error, reason } -> # uh oh end
  • 32. Pipe Operator |> Typical code in OOP / imperative programming: people = DB.find_customers orders = Orders.for_customers(people) tax = sales_tax(orders, 2013) filing = prepare_filing(tax) We could rewrite it as... filing = prepare_filing( sales_tax(Orders.for_customers( DB.find_customers), 2013))
  • 33. Pipe Operator |> With Elixir pipe operator we can do just filing = DB.find_customers |> Orders.for_customers |> sales_tax(2013) |> prepare_filing “|>” passes the result from the le! expression as the first argument to the right expression. Kinda like the Unix pipe “|”. It’s just useful syntax sugar.
  • 34. Mix • Mix is a build tool that ships with Elixir that provides tasks for creating, compiling, testing your application, managing its dependencies and much more. • Kind of like rake (Ruby) on steroids.
  • 35. Mix ➜ ~ mix --help mix # Runs the default task (current: "mix run") mix app.start # Starts all registered apps mix archive # Lists all archives mix archive.build # Archives this project into a .ez file mix archive.install # Installs an archive locally mix archive.uninstall # Uninstalls archives mix clean # Deletes generated application files mix cmd # Executes the given command mix compile # Compiles source files mix deps # Lists dependencies and their status mix deps.clean # Deletes the given dependencies' files mix deps.compile # Compiles dependencies mix deps.get # Gets all out of date dependencies mix deps.unlock # Unlocks the given dependencies mix deps.update # Updates the given dependencies mix do # Executes the tasks separated by comma mix escript.build # Builds an escript for the project mix help # Prints help information for tasks mix hex # Prints Hex help information mix hex.build # Builds a new package version locally mix hex.config # Reads or updates Hex config mix hex.docs # Publishes docs for package mix hex.info # Prints Hex information mix hex.key # Hex API key tasks mix hex.outdated # Shows outdated Hex deps for the current project mix hex.owner # Hex package ownership tasks mix hex.public_keys # Manages Hex public keys mix hex.publish # Publishes a new package version mix hex.registry # Hex registry tasks mix hex.search # Searches for package names mix hex.user # Hex user tasks mix loadconfig # Loads and persists the given configuration mix local # Lists local tasks mix local.hex # Installs Hex locally mix local.phoenix # Updates Phoenix locally mix local.public_keys # Manages public keys mix local.rebar # Installs rebar locally mix new # Creates a new Elixir project mix phoenix.new # Creates a new Phoenix v1.1.4 application mix profile.fprof # Profiles the given file or expression with fprof mix run # Runs the given file or expression mix test # Runs a project's tests iex -S mix # Starts IEx and run the default task
  • 36. Mixfile defmodule MyCoolProject.Mixfile do use Mix.Project def project do [ app: :my_cool_projet, version: "0.0.1", deps: deps ] end # Configuration for the OTP application def application do [mod: { MyCoolProject, [] }] end # Returns the list of dependencies in the format: # { :foobar, git: "https://github.com/elixir-lang/foobar.git", tag: "0.1" } # # To specify particular versions, regardless of the tag, do: # { :barbat, "~> 0.1", github: "elixir-lang/barbat" } defp deps do [ {:exactor, github: "sasa1977/exactor"}, {:"erlang-serial", github: "knewter/erlang-serial", app: false} ] end end
  • 37. DocTests defmodule MyModule do @doc ~S""" Sums two numbers ## Examples iex> MyModule.sum(1, 2) 3 """ def sum(a, b) do a + b end end $ mix test Compiled lib/my_module.ex .. Finished in 0.1 seconds (0.1s on load, 0.00s on tests) 2 tests, 0 failures Randomized with seed 307356
  • 38. OTP • OTP stands for Open Telecom Platform, but the name is misleading. OTP is not only for telecom related so!ware. • It’s a bundle that includes a large number of libraries to solve problems like state management, application discovery, failure detection, hot code swapping, and server structure . • Unfortunately, we don’t have time to talk about OTP today :/
  • 41. Phoenix Framework • MVC web framework created by Chris McCord. José Valim is working on it too. • Tastes a little bit like Ruby on Rails, but it is not. • Aims for high developer productivity and high application performance. • It has powerful abstractions for creating modern web apps in 2016, such as Channels (~ web sockets).
  • 42. Phoenix Framework • Create a new project $ mix phoenix.new hello_phoenix • Create database $ mix ecto.create • Run server $ mix phoenix.server
  • 43. Phoenix Framework • It’s actually the top layer of a multi-layer system designed to be modular and flexible. • The other layers include Plug (kind of like Ruby’s Rack), Ecto (kind of like ActiveRecord), and Cowboy, the Erlang HTTP server.
  • 44. Phoenix Framework • Thanks to the power of Elixir and the ease of use of Channels in Phoenix we can create web apps where we have 1 real time bi-directional data channel with every user (a websocket). And it scales, for real. • Despite that WebSockets are the main transport for Phoenix’s channels, it also supports other transport mechanism for old browsers or embedded devices.
  • 45. Phoenix Framework • It plays nicely with the modern front-end world (ES6) by relying on Brunch, a fast and simple asset build tool. • It’s very easy to replace Brunch by Webpack or any other hipster build tool of your choice. • Note that Brunch requires Node.js (trollface).
  • 51.
  • 53. Showcase • BSRBulb: Elixir library to control a Bluetooth Smart Bulb. https://github.com/diacode/bsr_bulb • Phoenix Trello: a Trello tribute with Phoenix & React. https://github.com/bigardone/phoenix-trello https://blog.diacode.com/trello-clone-with-phoenix-and-react-pt-1 • Phoenix Toggl: a Toggl tribute with Phoenix & React. https://github.com/bigardone/phoenix-toggl • Elixir Toggl API Wrapper https://github.com/diacode/togglex
  • 55. Next steps • Watch every talk by José Valim. Really, you won’t regret. • Books: Programming Elixir – Dave Thomas Programming Phoenix – Chris McCord, Bruce Tate & José Valim. • Elixir Getting Started Guide (really good!) http://elixir-lang.org/getting-started/introduction.html • Phoenix Guide (really good!) http://www.phoenixframework.org/docs/overview • Elixir Radar http://plataformatec.com.br/elixir-radar • Madrid |> Elixir Slack (#madrid-meetup) https://elixir-slackin.herokuapp.com/