Slide 1

Slide 1 text

Intro to Elixir from a 
 scripting language perspective

Slide 2

Slide 2 text

Matthew Lyon @mattly Ruby, Javascript/ CoffeeScript, Bash, Python, SQL, Max/MSP

Slide 3

Slide 3 text

What can this help me build? 2004, Rails: Web + SQL 2006, jQuery: sane frontend 2010, node: concurrent…?

Slide 4

Slide 4 text

What can this help me build? easily scalable software that doesn’t wake me up at 3am

Slide 5

Slide 5 text

erlang is awesome

Slide 6

Slide 6 text

erlang is awesome the VM

Slide 7

Slide 7 text

concurrency model lightweight processes actor pattern

Slide 8

Slide 8 text

OTP: “killer app” design principles library used to build systems w/ 99.9999999% uptime

Slide 9

Slide 9 text

syntax is… weird has a lot of gotchas {foo, State}:bar(1,2) foo:bar(1,2,{foo, State}) →

Slide 10

Slide 10 text

stdlib interfaces many inconsistencies ! lists:map(Fun, List) -> List2 string:substr(Str, Start, Length) -> SubString !

Slide 11

Slide 11 text

Ralph Waldo Emerson “Consistency is the hobgoblin of little minds.”

Slide 12

Slide 12 text

“Inconsistency is the hobgoblin of unmaintainable software.”

Slide 13

Slide 13 text

goto fail heartbleed !

Slide 14

Slide 14 text

Elixir created by rails-core 
 member Jose Valim

Slide 15

Slide 15 text

kinda like coffeescript but not really

Slide 16

Slide 16 text

plain syntax is 
 easier to read and reduces gotchas

Slide 17

Slide 17 text

thing, arguments ! Enum.map(list, fun) -> list2 String.slice(str, start, len) -> substr stdlib interfaces 
 are consistent

Slide 18

Slide 18 text

metaprogramming there when you want it, transparent when you don’t

Slide 19

Slide 19 text

it has amazing tooling
 great build system
 documentation
 doctests dependency management included testing library

Slide 20

Slide 20 text

it’s erlang semantics ! not ‘ruby compiling to erlang’ “CoffeeScript is just Javascript”

Slide 21

Slide 21 text

it compiles to erlang bytecode, integrates w/ existing ecosystem ! though you’ll have to learn a bit of erlang too ! similar to Clojure, Scala

Slide 22

Slide 22 text

unlearn you 
 some OOP 
 for great good

Slide 23

Slide 23 text

object-oriented is not the only good way to design software

Slide 24

Slide 24 text

functional programming doesn’t have to be mathematical or complex

Slide 25

Slide 25 text

assignment & control flow are not essential to programming

Slide 26

Slide 26 text

locks & semaphores 
 are not essential to concurrency

Slide 27

Slide 27 text

functional programming 
 treats computation as the evaluation of mathematical functions and avoids state and mutable data. Functional programming emphasizes functions that produce results that depend only on blah blah expressions blah blah blah declarative blah blah blah no side effects blah blah blah lambda calculus blah blah blah monads blah blah blah category theory source: wikipedia

Slide 28

Slide 28 text

functions transform
 data

Slide 29

Slide 29 text

functions are small, focused grep '/home' /etc/passwd

Slide 30

Slide 30 text

functions are composable grep '/home' /etc/passwd | wc -l

Slide 31

Slide 31 text

functions are repeatable grep '/home' /etc/passwd | wc -l 23

Slide 32

Slide 32 text

functions don’t have side-effects a = "hello" a.capitalize! # a = “Hello" ! a = String.capitalize(a)

Slide 33

Slide 33 text

functions don’t mutate state a = [3,2,1] a.reverse() // modifies a a.concat([4,5]) // new array ! a = Enum.reverse(a) a = Enum.concat(a, [4,5])

Slide 34

Slide 34 text

“How do we program without GOTO?” Computer Science, 1968

Slide 35

Slide 35 text

“How do we program without mutable state?” Computer Science, 2014

Slide 36

Slide 36 text

immutability 
 allows re-using memory

Slide 37

Slide 37 text

immutability 
 is the key to concurrency

Slide 38

Slide 38 text

that’s great… ! so, uh, how do I 
 build something?

Slide 39

Slide 39 text

Classes Instances behavior state

Slide 40

Slide 40 text

Classes Instances behavior state Modules Processes

Slide 41

Slide 41 text

Classes Instances behavior state Modules Processes you mean like, threads?

Slide 42

Slide 42 text

processes are light elixir --erl "+P 1000000" \ -r chain.exs \ -e "Chain.run(400_000)" {5325361, "Result is 400000"} that’s 400k processes 
 spawning sequentially, running simultaneously in 5.3 seconds on a MacBook Air

Slide 43

Slide 43 text

actors, not objects

Slide 44

Slide 44 text

actors send & receive messages

Slide 45

Slide 45 text

upon receiving a message, an actor may send a finite number of messages to other actors

Slide 46

Slide 46 text

upon receiving a message, an actor may create a finite number of other new actors


Slide 47

Slide 47 text

upon receiving a message, an actor may designate the behavior to be used for the 
 next message

Slide 48

Slide 48 text

but really 
 you don’t have to 
 think too much about it, thanks to OTP

Slide 49

Slide 49 text

first, how to write sequential code
 all over again

Slide 50

Slide 50 text

know your type(s)

Slide 51

Slide 51 text

base types Integers, 
 arbitrary precision Floats,
 IEEE 754 64-bit Atoms, aka symbols Tuples, not arrays Lists, not arrays Binaries, not strings Functions Pids, Ports, References

Slide 52

Slide 52 text

atoms :crypto the name is the value ! true, false, nil are atoms

Slide 53

Slide 53 text

tuples {:arbitrary, items, [1,2]} any element accessible in constant time

Slide 54

Slide 54 text

lists [:arbitrary, items, {1,2}] [:arbitrary|[items|[{1,2}]]] [head | tail] head accessible in constant time think of them like stacks

Slide 55

Slide 55 text

implemented types Strings, 
 using binaries or 
 “character lists” Records,
 using tuples Maps, aka dicts / 
 hashes / POJOs, 
 using Lists Streams, lazy-
 loaded enums Regexs, Ranges, Sets

Slide 56

Slide 56 text

ranges Enum.map(1..5, fn(i)-> i end) ! start, end can be any type enumeration requires integers

Slide 57

Slide 57 text

records defrecord RgbColor, red: 0, 
 blue: 0, green: 0 ! like loosely typed Structs

Slide 58

Slide 58 text

records RgbColor[red: 0.5, 
 blue: 100, 
 green: 'a7'] ! ! ! …really loose

Slide 59

Slide 59 text

records new_color =
 color.red(42) ! ! the only non-module type with functions

Slide 60

Slide 60 text

functions adder = fn(a) -> fn (b) -> a + b end end can pass as values

Slide 61

Slide 61 text

unnamed functions add2 = adder.(2) add2.(3) 5 remember original environment

Slide 62

Slide 62 text

inline functions Enum.map([1,2], 
 &(&1 * &1)) save needless fn declarations

Slide 63

Slide 63 text

composable inlines divrem = &{div(&1,&2), rem(&1,&2)} divrem.(13,5) # {2,3} lexer is pretty smart

Slide 64

Slide 64 text

detachable len = &Enum.count/1 ! great for composing functions

Slide 65

Slide 65 text

named functions defmodule Geometry do def area(item) do # math goes here end end

Slide 66

Slide 66 text

many small functions ! area doesn’t have to branch by shape type

Slide 67

Slide 67 text

pattern matching 
 assert, don’t assign

Slide 68

Slide 68 text

LHS = RHS

Slide 69

Slide 69 text

foo = 1 1 = foo ! these are assertions

Slide 70

Slide 70 text

foo = 1 1 = foo 2 = foo ** (MatchError) no match of right hand side value: 1

Slide 71

Slide 71 text

foo = 1 1 = foo ! identifiers on LHS are bound

Slide 72

Slide 72 text

foo = 1 1 = foo ^foo = 2 ** (MatchError) no match of right hand side value: 2

Slide 73

Slide 73 text

list = [1,4,9,16] [1,a|rest] = list 4 = a RHS compounds are destructured

Slide 74

Slide 74 text

list = [1,4,9,16] [2,a|rest] = list ** (MatchError) no match 
 of right hand side value: [1,4,6,9]

Slide 75

Slide 75 text

{Color, :rgb, {r,g,b}} = my_color ! destructuring can be used with any depth

Slide 76

Slide 76 text

! {n,_} = Float.parse("1.618") ! ignore unwanted values 
 with underscores

Slide 77

Slide 77 text

functions, reloaded

Slide 78

Slide 78 text

! defmodule Color do def hex(:rgb, vals={r,g,b}) do # no conversion needed function signatures 
 perform pattern matching

Slide 79

Slide 79 text

defmodule Factorial do def of(0), do: 1 def of(x), do: x * of(x-1) end declare multiple signatures instead of using if or case

Slide 80

Slide 80 text

defmodule Factorial do def of(0), do: 1 def of(x) when is_number(x) and x > 0, do: x * of(x-1) end guard clauses 
 augment pattern matching

Slide 81

Slide 81 text

Factorial.of(-100) ** (FunctionClauseError) no function clause matching in Factorial.of/1 guard clauses 
 are limited, but very useful

Slide 82

Slide 82 text

defmodule Factorial do def of(x) when is_number(x) and x > 0, do: of(x, 1) defp of(0,a), do: a defp of(x,a), do: of(x-1, a*x) end tail-call optimization 
 doesn’t add to the stack

Slide 83

Slide 83 text

! defmodule Color do def rgb(r\\0, g\\0, b\\0) do default values 
 match left-to-right save a ton of boilerplate

Slide 84

Slide 84 text

home = &(Regex.match?(~{/home},&1)) ! blob = File.read!('/etc/passwd') lines = String.split(blob, "\n") matches = Enum.filter(lines, home) initial = Enum.take(matches, 5) users = Enum.map(initial, get_user) without mutation… lots of asserting?

Slide 85

Slide 85 text

Enum.map( Enum.take( Enum.filter( String.split( File.read!( '/etc/passwd'), "\n"), home), 5), get_user) no… just… no

Slide 86

Slide 86 text

'/etc/passwd' |> File.read! |> String.split("\n") |> Enum.filter(home) |> Enum.take(5) |> Enum.map(get_user) pipeline operator result of expression on left is first param for fn on right

Slide 87

Slide 87 text

functions are composable echo '/etc/passwd' | xargs -n 1 cat | grep '/home' | head -n 5 | cut -d: -f 1

Slide 88

Slide 88 text

it’s easier to reason about small functions with no internal state

Slide 89

Slide 89 text

imagine there’s 
 no if statement ! you couldn’t if you tried

Slide 90

Slide 90 text

erlang doesn’t have if, but elixir does. it’s a macro.

Slide 91

Slide 91 text

! if x < 3, do: IO.puts "hello", else: IO.puts "bye" and that’s how you use a macro
 there’s also an unless macro

Slide 92

Slide 92 text

but please don’t use else with unless

Slide 93

Slide 93 text

if else? meet cond

Slide 94

Slide 94 text

result = cond do whole(val,3) and whole(val,5) -> "FizzBuzz" whole(val, 3) -> "Fizz" whole(val, 5) -> "Buzz" true -> val end you probably just want function calls instead

Slide 95

Slide 95 text

case or switch? we’ve got case ! hint: it uses pattern matching

Slide 96

Slide 96 text

! case thing do c = Color[type=:rgb, {r,g,b}] when is_number(r) and r < 1 -> pattern matching with guards & destructuring

Slide 97

Slide 97 text

unmatched cond clauses or case patterns will raise

Slide 98

Slide 98 text

exceptions? ! they’re for when something unanticipated happens

Slide 99

Slide 99 text

! case File.open("chain.exs") do { :ok, file } -> # something { :error, reason } -> # uh oh end this code anticipates a problem with file reading

Slide 100

Slide 100 text

file = File.open!("chain.exs") this code doesn’t ! elixir convention:
 ! functions raise on error

Slide 101

Slide 101 text

let it crash ! don’t make ad-hoc decisions when something goes wrong

Slide 102

Slide 102 text

do I actually know how I’m supposed to handle an error?

Slide 103

Slide 103 text

concurrency through smart sequences

Slide 104

Slide 104 text

actors are processes that talk and listen

Slide 105

Slide 105 text

Classes Instances behavior state Modules Processes processes are cheap

Slide 106

Slide 106 text

my god, 
 it’s full of processes 2001 by Stanley Kubrick

Slide 107

Slide 107 text

! pid = spawn(ModuleName,
 :function_name,
 [arg1, arg2]) spawning new processes is easy

Slide 108

Slide 108 text

! send(pid, [val1, val2]) sending messages is 
 fire & forget

Slide 109

Slide 109 text

def function_name(arg1, arg2) do receive do :hello -> IO.puts("hello") val -> do_something(val) end end receiving messages is straightforward and uses pattern matching

Slide 110

Slide 110 text

send(pid, {self, val1}) receive do response -> # handle ! def function_name(arg1, arg2) do receive do {p,v} -> send(p, process(v)) combine these 
 to wait for a response

Slide 111

Slide 111 text

each process 
 has its own mailbox ! receive reads the first message

Slide 112

Slide 112 text

def function_name(state) do receive do {p,v} -> send(p, process(v)) end function_name(new_state) end an actor 
 may designate the behavior 
 for the next message

Slide 113

Slide 113 text

tail-call optimization means we aren’t 
 adding to the stack

Slide 114

Slide 114 text

combine sending and receiving to parallelize

Slide 115

Slide 115 text

Parallel.map( 1..n, &Factorial.of/1) ! ! elixir -r par.exs -e “Parallel.fac(5000)” 5000 items, last is 422… took 13547672 microseconds

Slide 116

Slide 116 text

that was Factorial.of(n) for n in 1..5000 running simultaneously on all cores

Slide 117

Slide 117 text

beam lets you connect multiple VMs ! (beyond our scope)

Slide 118

Slide 118 text

the supervisor pattern is for managing processes

Slide 119

Slide 119 text

defmodule GhostWhisper do def talk_to_dead do exit(99) # impossible something went wrong? crash

Slide 120

Slide 120 text

{pid,ref} = Process.spawn_monitor( &GhostWhisper.talk_to_dead/0) receive do {:DOWN,^ref,:process,^pid,r} -> IO.puts(“#{inspect(pid)},#{r}”) monitoring tells you when
 a process dies

Slide 121

Slide 121 text

def dead_waiter do sleep 500; send(pid, "hi") ! spawn_link(GW,:dead_waiter,[self()]) receive do msg -> # never gets here after 100 -> exit(99) linking sets up process
 dependencies

Slide 122

Slide 122 text

extending with metaprogramming & monkeypatching ! (don’t worry, no actual monkeypatching)

Slide 123

Slide 123 text

macros are metaprogramming done right

Slide 124

Slide 124 text

homoiconicity the language has direct access to its own internal structures

Slide 125

Slide 125 text

hygenic macros won’t clobber each others’ variables or those of the functions that use them ! you can turn hygiene off

Slide 126

Slide 126 text

low-overhead macros modify the AST at compile time

Slide 127

Slide 127 text

defmacro if(condition, body) do yes = Keyword.get(body, :do, nil) no = Keyword.get(body, :else, nil) quote do case unquote(condition) do false -> unquote(no) _ -> unquote(yes) quote writes to the output tree unquote writes variable content

Slide 128

Slide 128 text

defmacro truthy(condition, body) do yes = Keyword.get(body, :do, nil) no = Keyword.get(body, :else, nil) quote do case unquote(condition) do val when val in [false, nil, 0, "", [], {}] -> unquote(no) _ -> unquote(yes) like javascript’s falsiness? here you go

Slide 129

Slide 129 text

defmacro dynamic_def(name) do quote bind_quoted: [name: name] do def unquote(name)() do unquote(name) ! [:red, :green] |> Enum.each(&Unholy.dynamic_def(&1)) want to dynamically define 
 methods at compile time? 
 use a binding

Slide 130

Slide 130 text

protocols are polymorphism for functions

Slide 131

Slide 131 text

think of them as 
 type-specific decorators

Slide 132

Slide 132 text

defimpl Enumerable, for: Bag do def count(collection) do # returns number of items in bag def member?(collection, value) # {:ok, boolean} def reduce(collection, acc, fun) # apply fun to the collection enables Enum to use Bag values

Slide 133

Slide 133 text

implemented types like Sets, Streams, Ranges use the Enumerable protocol

Slide 134

Slide 134 text

defimpl Access, for: Bag def access(container, key) # gets key from container ! my_bag[:thing] enables Bag variables 
 to use [] accessors

Slide 135

Slide 135 text

Inspect is a protocol, if you want to pretty- print your own types

Slide 136

Slide 136 text

behaviours are interface definitions for modules

Slide 137

Slide 137 text

erlang has a british- english influence, so get used to the brit spelling

Slide 138

Slide 138 text

defmodule My.Server do use GenServer.Behaviour @version 3 def init(initial) :: result def handle_call(request, from, state) 
 :: result def handle_cast(request, state) 
 :: result def handle_info(info, state) :: result def terminate(reason, state) def code_change(oldVsn, state, extra)
 :: status OTP server interface definition

Slide 139

Slide 139 text

declaring behaviour use and implelenting an interface lets you leverage powerful abstractions

Slide 140

Slide 140 text

great tooling 
 makes a 
 foreign environment easier

Slide 141

Slide 141 text

mix can throw down against rake, grunt, easy_install, npm, make, pip, & bundler

Slide 142

Slide 142 text

create projects, 
 manage deps, test, & compile, generate docs

Slide 143

Slide 143 text

documenation isn’t merely grafted on

Slide 144

Slide 144 text

defmodule MyModule do @moduledoc """ ## This is my module “"" ! iex(1)> h(MyModule) MyModule ## This is my module

Slide 145

Slide 145 text

@doc """ ignores its arg and returns 1 """ def function(_), do: 1 ! iex(2)> h(MyModule.function/1) def function(_) ignores its arg and returns 1

Slide 146

Slide 146 text

# mix.exs defp deps do [ { :ex_doc, github:'elixir-lang/ex_doc'} ] end ! $ mix docs ExDoc makes HTML docs for you

Slide 147

Slide 147 text

ExUnit leverages macros for the power of awesome

Slide 148

Slide 148 text

defmodule MathTest do use ExUnit.Case ! test "math is correct" do assert( 2 + 2 = 5 ) end end test and assert are macros

Slide 149

Slide 149 text

$ mix test Compiled lib/test/supervisor.ex Compiled lib/test.ex Generated test.app 1) test math is correct (MathTest) ** (ExUnit.ExpectationError) expected: 5 to match pattern (=): 2 + 2 at test/math_test.exs:5 assertion types are implied 
 by pattern matching & syntax tree

Slide 150

Slide 150 text

the OTP sales pitch ! (sadly beyond our scope)

Slide 151

Slide 151 text

libraries implementing best-practice patterns

Slide 152

Slide 152 text

write your servers, state machines, event handlers & supervisors 
 to a common 
 abstract interface

Slide 153

Slide 153 text

def current_state_name(:event_name, details) do # transition logic { :next_state, :new_state_name, details } end ! def new_state_name(:event_name, …) the state machine DSL is sexy

Slide 154

Slide 154 text

leverage battle-tested patterns, tools for debugging, release management & more

Slide 155

Slide 155 text

it’s still a young community, 
 but building on old infrastructure

Slide 156

Slide 156 text

No content

Slide 157

Slide 157 text

elixir-lang.org elixirsips.com Programming Elixir by Dave Thomas Elixir in Action by Saša Jurić

Slide 158

Slide 158 text

erlang.org Programming Erlang by Joe Armstrong Learn You Some Erlang For Great Good by Frank Hébert learnyousomeerlang.com our meetup hosts, erlangsolutions.com

Slide 159

Slide 159 text

thank you! ! Matthew Lyon twitter / github: mattly speakerdeck.com/mattly/intro-to-elixir ! typefaces: Source Sans Pro & Source Code Pro and ChunkFive