Erlang Introduction
Erlang Introduction
1
Philosophy of Erlang
2
Erlang Mindset
3
Why Erlang?
4
Erlang makes hard things
easier.
5
Concurrency
6
7
Spawning Processes
8
F = fun() ->
io:format(hi)
end,
spawn(F).
>> hi<0.34.0>
9
spawn(io, format, [hi]).
10
Message Passing
11
12
Pid ! Message
Pid ! 2
13
receive ... end
receive
Pattern1 [when Guard1] ->
Expressions1;
Pattern2 [when Guard2] ->
Expressions2
end.
14
Messages are contained in a processs
inbox.
receive
_ ->
ok
end.
15
Fault Tolerance
16
17
18
which is why erlang was
designed to be....
19
Distributive
20
21
Pid ! Message
22
Erlang Nodes
Can only talk if the erlang cookie is the same
Can exist on the same machine or different machines
Does have overhead, isnt free
Can have C nodes (+ other node types that speak
erlang)
Communicate via Global Name Registry, Specific Pids,
or by Node name
23
The Basics
24
Erlang is Functional
25
Periods, Commas,
Semicolons Oh My!
People think Erlangs syntax is ugly. Its actually
very logical.
26
Periods ( . ) end everything except when
27
calculate_area({square, Size}) ->
Size * Size;
calculate_area(_Unknown) ->
ok.
28
case Expression of
{do_task, run_home} ->
Home = 123,
spawn(run, home, [Home]);
_ ->
ok
end.
29
Data Types
30
Integer - however big you can imagine
Floats
31
Missing Links...
32
Strings - A string is just a list of integers in erlang.
33
Pattern Matching
Once you pattern match, variable assigning feels dirty.
34
1 = 1 ( ok )
[Head|Tail] = [1,2,3,4] ( ok )
35
Variable Binding
or restricting infinite possibilities.
36
An unbound variable can be anything it
needs to be (infinite possibilities)
A.
37
Pattern matching an unbound variable is
like restricting what it can be.
A = 1.
A = 2. (error bad_match)
38
Tuples
Single entity that holds a collection of items.
39
{1, 2, 3}.
{one, two}.
40
Lists
Variable sized container of items.
41
List = [1, 2, 3],
NewList = List ++ [4, 5, 6].
>> [1, 2, 3, 4, 5, 6]
[Head|Tail] = NewList.
>> Head -> 1
>> Tail -> [2, 3, 4, 5, 6]
42
[tuple()]
Property Lists or semi-hashes.
43
PList = [{key, value}, {key1, value1}].
44
keydelete - deletes tuple with specified key in list of
tuples and returns new list
45
Functions
Pattern matching, Function Arities & more
46
Functions with the same name can exist
47
contains(Key, []) ->
false;
contains(Key, List) ->
lists:any(fun(X) -> Key == X end, List).
48
Anonymous
49
contains(Key, []) ->
false;
contains(Key, List) ->
lists:any(fun(X) -> Key == X end, List).
F = fun(X, Y) ->
X1 = X * 2,
Y1 = Y * X,
X1 + Y1
end,
F(2, 2).
>> 12
50
Looping
Tail recursion makes looping good again.
51
print([]) ->
ok;
print([H|T]) ->
io:format(~p~n, [H]),
print(T).
52
Conditionals
Ifs are okay, cases are cooler.
53
if
A == 5 ->
do_something();
true ->
do_something_else()
end.
54
case A of
0 ->
first();
2 ->
second();
_ ->
something()
end.
55
Resources
http://www.erlang.org
Technorati
56
57
Questions?
58