Slides for the "Introduction to Elixir" talk I gave at the first Elixir/Erlang meetup in Italy, set in Bologna (October 2015).
introduction toElixir
View Slide
Erlangcompiles tobytecode
Elixir is what would happen if Erlang, Clojure andRuby somehow had a baby and it wasn't anaccidentDevin Torres
Andrea Leopardi@whatyouhide
metaprogrammingtoolinginteropconcurrencyfeatures
features
data structures
199"t-rex":dr_manhattan[:red, :white, :blue]{:error, "nope"}%{hair: :red, weight: :high}
immutability
all data structuresare immutable
animals = ["lion", "table", "bear"]List.delete(animals, "table")animals#=> ["lion", "table", "bear"]
data+functions
datafunctionsmodules
String.upcase("meh")modulefunctiondata
defmodule String dodef upcase(str) do# ...endend
high-order functions
doubler = fn(i) -> i * 2 endEnum.map([1, 2, 3], doubler)#=> [2, 4, 6]
pattern matching
= ≠ =
match the structure of the databind variables while doing that
[first, second, third] = [:houston,:austin,:dallas,] first#=> :houstonsecond#=> :austin
[first, second, _] = [:houston,:austin,:dallas,] first#=> :houstonsecond#=> :austin
[first, second, _] = [:houston,:austin,:dallas,:seattle,]** (MatchError)
protocols
à la Clojure
JSON.encode(thing)defines API
defprotocol JSON dodef encode(thing)end
JSON.encode(thing)dispatches to implementation
defimpl JSON, for: Integer dodef encode(i), do: # ...end
concurrency
Any sufficiently complicatedconcurrent program in anotherlanguage contains an ad hocinformally-specified bug-riddenslow implementation of half ofErlang. Robert Virding
spawn fn ->IO.puts "from another process"end
not OSprocesses
lightweightisolationmessage passing
for _ spawn(fn -> :ok end)endlightweight
animals = [:dog, :cat]spawn fn ->animals # it's a copyendisolation
isolationper-process garbagecollection!!!
message passingthe only wayprocesses cancommunicate
pid = spawn fn -># ...endsend pid, "a message"message passing
spawn fn ->receive domsg -> :okendendmessage passing
spawn_monitor fn ->raise "die!"endreceive do m -> m end#=> {:DOWN, ...}message passing
actor model
def loop(state) doreceive do{from, :get} ->send(from, state)loop(state){from, :put, new_state} ->loop(new_state)endend
def loop(state) doreceive do{from, :get} ->send(from, state)loop(state){from, :put, new_state} ->loop(new_state)endend spawn(&loop/0)
Node.spawn(node, fun)
interop
Elixir data structuresareErlang data structures
lists:map(fun(X) -> X * 2 end,[1, 2, 3]).:lists.map(fn(x) -> x * 2 end,[1, 2, 3])
:queue.in("customer1",:queue.new())
tooling
iex> 8 * 216IEx
mix new my_appcompiletestdeps.getMix
test "math works!" doassert 1 + 1endExUnit
Hey there, !EEx
defp deps do[{:phoenix, "~> 1.0"},{:ecto, "~> 1.0"}]endHex
so
lots of companies use Elixir in prodit's awesome to work withthriving ecosystem, smart devsphoenixmetaprogramming
@whatyouhide