Erlang bootstrap course
Upcoming SlideShare
Loading in...5
×
 

Erlang bootstrap course

on

  • 3,069 views

This presentation is part of a talk by Martin j. Logan on the essentials of programming in the erlang language. The talk covers:...

This presentation is part of a talk by Martin j. Logan on the essentials of programming in the erlang language. The talk covers:

Data Types
Modules and Functions
State Management
Distribution
Fault Tolerance

The code for this talk can be found at github:

git://github.com/martinjlogan/ErlangBootstrap.git
https://github.com/martinjlogan/ErlangBootstrap

Statistics

Views

Total Views
3,069
Views on SlideShare
2,802
Embed Views
267

Actions

Likes
3
Downloads
29
Comments
0

7 Embeds 267

http://lanyrd.com 190
http://www.linkedin.com 36
http://erlangs.ru 27
https://www.linkedin.com 9
https://twitter.com 2
http://www.slashdocs.com 2
http://twitter.com 1
More...

Accessibility

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Note the use of "_", the anonymous (don't care) variable.\n Note the use of _Tail. This is also a don't care var that instructs \n the compiler not to produce a warning. It equally efficient as _ and preferred. \n\n
  • \n
  • \n
  • \n
  • * double can be called from outside the module, times is local to the module.\n * double/1 means the function double with one argument (Note that double/1 and double/2 are two different functions). \n\nLets put our todo list into a module. Show module todo_list.erl from code section.\n
  • \n
  • * Are in the module erlang.\n * Do what you cannot do (or is difficult to do) in Erlang.\n * Modify the behaviour of the system.\n * Described in the BIFs manual. \n
  • Show the module todo_list at hash \n
  • Doing something more with lists involved the use of lambda functions\n
  • Next we use the example file in git called fib.erl to show iteration via recursion and the use of case and function head pattern matching.\n
  • Next we use the example file in git called fib.erl to show iteration via recursion and the use of case and function head pattern matching.\n
  • \n
  • Where the hell is the state in Erlang?\n
  • State is held in process loops. Messaging is your big old global variable should you choose to use it that way. But the one difference is, messaging is copy everything share nothing. No shared state then. The yoke of the tyrant is off almost - this is still a side effect. It may not deadlock but it can still result in the unexpected.\n
  • Keep your side effects isolated\n
  • \n
  • \n
  • self() - returns the Process Identity or "Pid" of the process executing this function.\n
  • \n
  • \n
  • \n
  • \n
  • Can anyone tell me why this is horrible. \nBreaks all kinds of encapsulation rules. That will be a topic for later though. \n
  • \n
  • \n
  • This is a picture of exit signals propagating through links. \n
  • \n
  • Supervision and layering\nThe result processor processes don’t care what happens to the lower level processes so long as they produce complete results at an acceptable frequency. \nDoes not get much cooler. Targus proxy at vail lived through a storm of shit. \nMini reboots - just like windows only smaller\n
  • \n
  • \n
  • \n
  • \n

Erlang bootstrap course Erlang bootstrap course Presentation Transcript

  • TheErlang Bootstrap Class The Erlang Basics Based on the 4 day Erlang course
  • What are we dealing with?Data TypesPattern Matching (makes functions fun)ModulesProcesses
  • Shell (learn it, love it)As critical to Erlang dev as fingersYour best tool for learning and experimentingImportant facts Start with erl Stop with ctrl c, ctrl c q(). to kill nicely expressions end in a period
  • Shell Commandsh() - history . Print the last 20 commands.b() - bindings. See all variable bindings.f() - forget. Forget all variable bindings.f(Var) - forget. Forget the binding of a variable Var. * This can ONLY be used as a command to * the shell - NOT in the body of a function!e(n) - evaluate. Evaluate the n:th command in history.e(-1) - Evaluate the previous command. * Edit the command line as in Emacs * See the User Guide for more details and examples of use of the shell.
  • Calculations in the Shell You
can
add!1> 1 + 1.2 You
can
assign
values
to
variables!2> X = 2.23> X + 1.3
  • Integers as you would expect But,
whah???4> Y =1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111. On
no
he
di’int!5> Y + 1.11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111112
  • Floats Alas,
not
freaky
(plain
ol’
64
bit
double‐precision)6> 1.1234567890123456789012345678901234567890.1.1234567890123457 An
unusual
conversion
from
float
to
int1> X = 1.12345.1.123452> is_float(X).true3> Y = erlang:trunc(X).14> is_integer(Y).true
  • ListsMost common data structure. Used for storing a variablenumber of elements.[123, xyz][ {person, Joe, Armstrong}, {person, Robert, Virding}, {person, Mike, Williams}]
  • Strings (haven’t we seen these before?)PreGy
much
what
you’d
expect 1> Slogan = "Mongo DB is Web Scale". "Mongo DB is Web Scale"But,
wait,
OMG,
noooo! 2> io_lib:format("Mongo DB is ~s", ["Web Scale"]). [77,111,110,103,111,32,68,66,32,105,115,32,"Web Scale"]Yep,
strings
are
just
lists! 3> is_string(Slogan). ** exception error: undefined shell command is_string/1 4> is_list(Slogan). true
  • BinariesSomeMmes
used
to
represent
strings <<"This is a binary">>is_binary
differenMates
from
is_listMore
typically
used
to
work
with
actual
binary
data







(e.g.
bitstring
syntax
–
not
covered
in
this
presentaMon)Have
protocol,
will
use
binaries/bitstrings!
  • Variables (not very variable)More of a definition than a variable. They dont actuallyever varyAbcA_long_non_standard_variable_nameAProperErlangVariableName * Start with an Upper Case Letter. * No "funny characters". * Variables are used to store values of data structures.
  • Tuplespretty much the “struct” thingy for erlang{123, bcd}{abc, {def, 123}, jkl}{}{atom() = Tag, term() = Value} % very erlangy{error, {“value was bad”, 9}}
  • Pattern Matching
  • A = 10Succeeds - binds A to 10{B, C, D} = {10, foo, bar}Succeeds - binds B to 10, C to foo and Dto bar{A, A, B} = {abc, abc, foo}Succeeds - binds A to abc, B to foo{A, A, B} = {abc, def, 123}Fails[A,B,C] = [1,2,3]Succeeds - binds A to 1, B to 2, C to 3[A,B,C,D] = [1,2,3]Fails
  • [A,B|C] = [1,2,3,4,5,6,7]Succeeds - binds A = 1, B = 2,C = [3,4,5,6,7][H|T] = [1,2,3,4]Succeeds - binds H = 1, T = [2,3,4][H|T] = [abc]Succeeds - binds H = abc, T = [][H|T] = []Fails{A,_, [B|_Tail],{B}} = {abc,23,[22,x],{22}}Succeeds - binds A = abc, B = 22
  • Modules & Functions
  • ToDo ListLet’s
make
a
list! 1> ToDo = ["Shard /dev/null", "Learn Ruby", "Remove Bing from Phone"].Write
to
disk
(easy
to
encode
Erlang!) 2> file:write_file("todo.bin", term_to_binary(ToDo)). okRead
from
disk
(easy
to
decode
Erlang!) 3> {ok, Bin} = file:read_file("todo.bin"). {ok,<<131,108,0,0,0,3,107,0,15,83,104,97,114,100,32,47, 100,101,118,47,110,117,108,108,107,0,10,...>>} 4> binary_to_term(Bin). ["Shard /dev/null","Learn Ruby","Remove Bing from Phone"]
  • Standard LibrariesSecond
most
important
Erlang
developer
tool:
a
decent
module
reference hGp://erlang.org/doc/man_index.html hGp://erldocs.com/
The
file
module
provides
an
interface
to
the
file
systemWe
will
keep
using
them
–
keep
an
eye
out
  • Module System-module(demo).-export([double/1]).double(X) -> times(X, 2).times(X, N) -> X * N.
  • Using listsComma
separated
Erlang
terms
surrounded
by
brackets [this, is, "a", {List, [of, stuff]}]Used
ehhhverywhereAn
important
paGern
for
iteraMve
operaMons lists:map/2 list
comprehensionThe
basis
for
“associaMve
array”
structure
in
Erlang
(proplist)
[{foo, "Foo" 123}]1> L1 = [2, 3].[2,3]2> L2 = [1|L1].[1,2,3]3> [H|T] = L2.[1,2,3]4> H.15> T.[1,2]
  • Built In Functions (BIFs)date()time()length([1,2,3,4,5])size({a,b,c})atom_to_list(an_atom)list_to_tuple([1,2,3,4])integer_to_list(2234)tuple_to_list({})
  • Lets do something more with lists A
basic
sort 5> lists:sort(ToDo). ["Learn Ruby","Remove Bing from Phone","Shard /dev/null"] Wait,
that’s
not
what
I
want! 6> ToDo2 = [{2, "Shard /dev/null"}, {3, "Learn Ruby"}, {1, "Remove Bing from Phone"}]. 7> lists:sort(ToDo2). [{1,"Remove Bing from Phone"}, {2,"Shard /dev/null"}, {3,"Learn Ruby"}] Default
sort
comparison
uses
“natural
order”
of
Erlang
term We
don’t
need
no
sMnking
natural
order! 8> lists:sort( fun({P1, N1}, {P1, N2}) -> N1 < N2 end, ToDo2). [{3,"Learn Ruby"}, {1,"Remove Bing from Phone"}, {2,"Shard /dev/null"}
  • Lambda FunctionsUse
fun
to
create
a
funcMon
from
within
a
funcMonUse
a
fun
to
pass
funcMonality
around
like
any
other
data
structureAnonymous
funcMons
have
access
to
variables
visible
within
their
defining
block,
even
when
executed
elsewhere 1> X = 1. 1 2> F = fun(Y) -> X + Y end. #Fun<erl_eval.6.13229925> 3> F(10). 11
  • Function HeadsIs defined as a collection of clauses.func(Pattern1, Pattern2, ...) ->... ;func(Pattern1, Pattern2, ...) ->... ;...func(Pattern1, Pattern2, ...) ->... .
  • Guardsis_number(X) - X is a numberis_integer(X) - X is an integeris_float(X) - X is a floatis_atom(X) - X is an atomis_tuple(X) - X is a tupleis_list(X) - X is a listlength(X) == 3 - X is a list of length 3size(X) == 2 - X is a tuple of size 2.X > Y + Z - X is > Y + Z
  • The Tyrannical State
  • The StateNo ObjectsNo GlobalsLogic VariablesNo Pass by Reference
  • In the LoopYour State
  • Side Effects- Side effects are not “evil”- any IO is a side effect- anything not “referentially transparent”- Make function substitution difficult- Side effects can catch you offguard. Be prepared.
  • Concurrent Programming
  • Creating a New ProcessCode in Pid1Pid2 = spawn(Mod, Func, Args)AfterPid2 is process identifier of the new process -this is known only to process Pid1.
  • Message Passing {PidA, foo} A B receivePidB ! {self(), foo} {From, Msg} -> Actions end
  • Echo Client-module(echo).-export([go/0]).go() -> Pid2 = spawn(fun() -> loop() end), Pid2 ! {self(), hello}, receive {Pid2, Msg} -> io:format("P1 ~w~n",[Msg]) end, Pid2 ! stop.
  • Echo Serverloop() -> receive {From, Msg} -> From ! {self(), Msg}, loop(); stop -> true end.
  • Selective Message Reception first foo then bar A receivePidC ! foo foo -> ... C end, receive bar -> ... end BPidC ! bar
  • sleep(T) -> receive after T -> true flush() -> end. receive {echo, Msg} -> flush()suspend() -> after receive 0 -> true after end. infinity -> true end.
  • Beefy Echo- Not just echo anymore- Fun with Funs- Call a process by a name
  • Now it gets interesting Fault Tolerance
  • Exit Signals EXIT EXIT EXITExit Signals are Sent when Processes Crash When a processcrashes (e.g. failure of a BIF or a pattern match) Exit Signalsare sent to all processes to which the failing process iscurrently linked.
  • A EXIT B EXIT C F EXIT EXITD EXIT E
  • Trap Exit = TrueProcesses can trap exit signalsIn the following diagram P1 is linked to P2 and P2 is linked toP3. An error occurs in P1 - the error propagates to P2. P2traps the error and the error is not propagated to P3. EXIT trap link exits
  • Put up with Sh!tresult parsed input data stream
  • Distribution
  • Single VM Single machine communication VM A on Machine A Y ! msg X Y VM A on Machine A VM B on Machine B Y ! msg X Y Multiple VM network communication
  • Registered process local communication VM A on Machine A reg ! msg X reg VM A on Machine A VM B on Machine B {reg, B} ! msg X regRegistered process network communication
  • Topology with Cookieserl -name <name> -setcookie foo erl -name <name> -setcookie bar