0
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  ...
Shell Commandsh() - history . Print the last 20 commands.b() - bindings. See all variable bindings.f() - forget. Forget al...
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 =1111111111111111111111111111111111111111111111111111111111111111111111111...
Floats   Alas,
not
freaky
(plain
ol’
64
bit
double‐precision)6> 1.1234567890123456789012345678901234567890.1.1234567890123...
ListsMost common data structure. Used for storing a variablenumber of elements.[123, xyz][    {person, Joe, Armstrong},   ...
Strings (haven’t we seen these before?)PreGy
much
what
you’d
expect   1> Slogan = "Mongo DB is Web Scale".   "Mongo DB is ...
BinariesSomeMmes
used
to
represent
strings   <<"This is a binary">>is_binary
differenMates
from
is_listMore
typically
used
...
Variables (not very variable)More of a definition than a variable. They dont actuallyever varyAbcA_long_non_standard_variab...
Tuplespretty much the “struct” thingy for erlang{123, bcd}{abc, {def, 123}, jkl}{}{atom() = Tag, term() = Value} % very er...
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, ab...
[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]...
Modules & Functions
ToDo ListLet’s
make
a
list!   1> ToDo = ["Shard /dev/null",              "Learn Ruby",              "Remove Bing from Phon...
Standard LibrariesSecond
most
important
Erlang
developer
tool:
a
decent
module
reference   hGp://erlang.org/doc/man_index....
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
...
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_...
Lets do something more with lists  A
basic
sort     5> lists:sort(ToDo).     ["Learn Ruby","Remove Bing from Phone","Shard...
Lambda FunctionsUse
fun
to
create
a
funcMon
from
within
a
funcMonUse
a
fun
to
pass
funcMonality
around
like
any
other
data...
Function HeadsIs defined as a collection of clauses.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...
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 functio...
Concurrent Programming
Creating a New ProcessCode in Pid1Pid2 = spawn(Mod, Func, Args)AfterPid2 is process identifier of the new process -this is ...
Message Passing                       {PidA, foo}        A                                  B                             ...
Echo Client-module(echo).-export([go/0]).go() ->  Pid2 = spawn(fun() -> loop() end),  Pid2 ! {self(), hello},  receive    ...
Echo Serverloop() ->  receive    {From, Msg} ->      From ! {self(), Msg},      loop();    stop -> true   end.
Selective Message Reception first foo then bar    A                         receivePidC ! foo                 foo -> ...   ...
sleep(T) ->  receive  after   T -> true        flush() ->  end.               receive                      {echo, Msg} -> fl...
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 Proce...
A            EXIT     B                   EXIT            C                 F    EXIT                          EXITD      ...
Trap Exit = TrueProcesses can trap exit signalsIn the following diagram P1 is linked to P2 and P2 is linked toP3. An error...
Put up with Sh!tresult          parsed    input           data    stream
Distribution
Single VM Single machine communication       VM A on Machine A                      Y ! msg              X                ...
Registered process local communication        VM A on Machine A                       reg ! msg               X           ...
Topology with Cookieserl -name <name> -setcookie foo                                  erl -name <name> -setcookie bar
Upcoming SlideShare
Loading in...5
×

Erlang bootstrap course

3,175

Published on

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

Published in: Technology, News & Politics
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,175
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
42
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Note the use of &quot;_&quot;, the anonymous (don&apos;t care) variable.\n Note the use of _Tail. This is also a don&apos;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 &quot;Pid&quot; 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&amp;#x2019;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
  • Transcript of "Erlang bootstrap course"

    1. 1. TheErlang Bootstrap Class The Erlang Basics Based on the 4 day Erlang course
    2. 2. What are we dealing with?Data TypesPattern Matching (makes functions fun)ModulesProcesses
    3. 3. 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
    4. 4. 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.
    5. 5. Calculations in the Shell You
can
add!1> 1 + 1.2 You
can
assign
values
to
variables!2> X = 2.23> X + 1.3
    6. 6. Integers as you would expect But,
whah???4> Y =1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111. On
no
he
di’int!5> Y + 1.11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111112
    7. 7. 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
    8. 8. ListsMost common data structure. Used for storing a variablenumber of elements.[123, xyz][ {person, Joe, Armstrong}, {person, Robert, Virding}, {person, Mike, Williams}]
    9. 9. 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
    10. 10. 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!
    11. 11. 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.
    12. 12. Tuplespretty much the “struct” thingy for erlang{123, bcd}{abc, {def, 123}, jkl}{}{atom() = Tag, term() = Value} % very erlangy{error, {“value was bad”, 9}}
    13. 13. Pattern Matching
    14. 14. 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
    15. 15. [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
    16. 16. Modules & Functions
    17. 17. 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"]
    18. 18. 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
    19. 19. Module System-module(demo).-export([double/1]).double(X) -> times(X, 2).times(X, N) -> X * N.
    20. 20. 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]
    21. 21. 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({})
    22. 22. 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"}
    23. 23. 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
    24. 24. Function HeadsIs defined as a collection of clauses.func(Pattern1, Pattern2, ...) ->... ;func(Pattern1, Pattern2, ...) ->... ;...func(Pattern1, Pattern2, ...) ->... .
    25. 25. 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
    26. 26. The Tyrannical State
    27. 27. The StateNo ObjectsNo GlobalsLogic VariablesNo Pass by Reference
    28. 28. In the LoopYour State
    29. 29. 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.
    30. 30. Concurrent Programming
    31. 31. 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.
    32. 32. Message Passing {PidA, foo} A B receivePidB ! {self(), foo} {From, Msg} -> Actions end
    33. 33. 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.
    34. 34. Echo Serverloop() -> receive {From, Msg} -> From ! {self(), Msg}, loop(); stop -> true end.
    35. 35. Selective Message Reception first foo then bar A receivePidC ! foo foo -> ... C end, receive bar -> ... end BPidC ! bar
    36. 36. sleep(T) -> receive after T -> true flush() -> end. receive {echo, Msg} -> flush()suspend() -> after receive 0 -> true after end. infinity -> true end.
    37. 37. Beefy Echo- Not just echo anymore- Fun with Funs- Call a process by a name
    38. 38. Now it gets interesting Fault Tolerance
    39. 39. 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.
    40. 40. A EXIT B EXIT C F EXIT EXITD EXIT E
    41. 41. 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
    42. 42. Put up with Sh!tresult parsed input data stream
    43. 43. Distribution
    44. 44. 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
    45. 45. 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
    46. 46. Topology with Cookieserl -name <name> -setcookie foo erl -name <name> -setcookie bar
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×