SlideShare a Scribd company logo
1 of 158
Download to read offline
Erlang Introduction



                      1
2
3
4
5
6
7
8
Syntax



         9
Hello User



             10
erl



      11
$ erl
1> |




        12
1> io:format(quot;Hello User~nquot;, []).
Hello User
ok




                                    13
2> 1 + 2008.
2009




               14
3> 1 + 2 + 3.
6




                15
10> 1 + 2 * 3.
7
11> 2 * 3 + 1.
7
12> (1 + 2) * 3.
9




                   16
13> 3/0.
** exception error: bad argument in an
arithmetic expression
     in operator '/'/2
         called as 3 / 0




                                         17
4> catch 3/0.
{'EXIT',{badarith,[{erlang,'/',[3,0]},
                   {erl_eval,do_apply,5},
                   {erl_eval,expr,5},
                   {shell,exprs,6},
                   {shell,eval_exprs,6},
                   {shell,eval_loop,3}]}}




                                        18
15> quot;Erlang introquot;.
quot;Erlang introquot;




                      19
35> quot;abcquot; ++ quot;defquot;.
quot;abcdefquot;




                      20
27> [72, 101, 108, 108, 111].
quot;Helloquot;




                                21
27> [$E, $r, $l, $a, $n, $g].
quot;Erlangquot;




                                22
Atom



       23
6> atom.
atom




           24
ok
true
false
kernel
erlang
'EXIT'
'Name'




         25
6> is_atom(zbar).
true

9> 1 == 3.
false




                    26
Use Functions



                27
36> lists:reverse(quot;nilreB olleHquot;).
quot;Hello Berlinquot;




                                     28
1> Mod = lists.
lists
2> Fn = reverse.
reverse
3> Mod:Fn(quot;tacquot;).
quot;catquot;




                    29
5> Mod:(list_to_atom(quot;reversequot;))(quot;atequot;).
quot;etaquot;




                                           30
37> apply(lists, reverse, [quot;nilreBquot;]).
quot;Berlinquot;




                                         31
39> Fn = fun lists:reverse/1.
#Fun<lists.reverse.1>
40> apply(Fn, [quot;olleHquot;]).
quot;Helloquot;




                                32
Variables



            33
48> N = 1.
1
49> N = 2.
** exception error: no match of right
hand side value 2
50> N = 1.
1




                                        34
Pattern matching
  and Variables


                   35
1> Coffee = harem:espresso().
{espresso, quot;Haremquot;, orange}
2> {espresso, _, Crema} = Coffee.
{espresso, quot;Haremquot;, orange}
3> Crema.
orange




                                   36
Data Structures



                  37
[101, left, right, $a, [0, 1, 2], quot;abcquot;]




                                           38
5> L = [101, left, right, quot;abcquot;].
[101,left,right,quot;abcquot;]

6> lists:nth(1,L).
101




                                    39
7> lists:nthtail(1, L).
[left,right,quot;abcquot;]




                          40
29> [66, 101 | quot;rlinquot;].
quot;Berlinquot;




                          41
38> [First, Sec | Rest] = quot;Restquot;.
quot;Restquot;
39> First.
82
40> [First].
quot;Rquot;
41> Sec.
101
42> [Sec].
quot;equot;



                                    42
Strings sind Listen




                      43
Tuple



        44
{1, 2, 3}




            45
1> P = {adam,24,{july,29}}.
{adam,24,{july,29}}
2> element(1,P).
adam




                              46
3> element(3,P).
{july,29}




                   47
4> P2 = setelement(2,P,25).
{adam,25,{july,29}}




                              48
5> tuple_size(P).
3




                    49
Binaries



           50
<<13, 10, 13, 10>>




                     51
<<quot;GET / HTTP/1.1quot;>>




                       52
web_request(Req) ->
    Req:ok({quot;text/htmlquot;,
    <<quot;<html>
        <head><title>
           Hello Berlin
        </title></head>
        <body>
            Hello Berlin
        </body>
      </html>quot;>>}).



                           53
54
0000000   d4   c3   b2   a1   02   00   04   00   00   00   00   00   00   00   00   00
0000010   60   00   00   00   01   00   00   00   07   aa   f7   48   b4   32   08   00
0000020   4e   00   00   00   4e   00   00   00   00   14   6c   62   ef   18   00   19
0000030   e3   07   c0   bc   08   00   45   00   00   40   30   0d   40   00   40   06
0000040   3e   4e   c0   a8   b2   cb   d1   55   87   93   cd   b9   00   50   a1   59
0000050   7f   98   00   00   00   00   b0   02   ff    ff    ad   c0   00   00   02   04
0000060   05   b4   01   03   03   03   01   01   08   0a   27   c0   a6   25   00   00
0000070   00   00   04   02   00   00
0000076




                                                                                          55
<<Version:4, IHLen:4,
  TOService:8, TotalLength:16,
  Id:16,       Flags:3, FragOffset:13,
  Ttl:8,       Protocol:8,
  HeaderChecksum:16,
  SourceAddr:32,
  DestAddr:32>> = H.




                                        56
43> A = 0.
0
44> B = 8.
8
45> C = 15.
15
46> Msg = <<A:9, B:12, C:16>>.
<<0,0,64,0,15:5>>




                                 57
dict
 array
  sets
  sofs
digraph




          58
Module file



             59
-module(forest).
-export([tree/1, tree/2]).

-include_lib(quot;kernel/include/
flora.hrlquot;).

%% External API

tree(Age) ->
    {tree, Age}.
tree(Age, Kind) ->
    {tree, Age, Kind}.


                                60
forest.erl



             61
$ erlc forest.erl



                    62
forest.beam



              63
Define Functions



                  64
double(X) ->
  2 * X.

greet(Name) ->
  io:fwrite(quot;Hallo ~p~nquot;, [Name]),
  ok.




                                     65
1, 2, 3, 5, 8, 13, 21, 34, 55, 89



                                    66
fib(0) ->
  0;
fib(1) ->
  1;
fib(N) when is_integer(N) ->
  fib(N-1) + fib(N-2).

                              67
For Want Of Loop



                   68
Recursion



            69
vowels(Text) ->
  vowels(Text, []).

vowels([H|T], Acc) ->
  Acc1=case member(H, quot;aeiuoquot;) of

     true -> [H | Acc];

     false -> Acc

 end,
  vowels(T, Acc1);
vowels([], Acc) ->
  reverse(Acc).



                                    70
foo(N) when N > 1 ->
  ok.




                       71
bar(N) when is_list(N), length(N) ->




                                       72
baz(I) when I > 0, I < 9 ->




                              73
quux(K) when I =< 0 or I >= 9 ->




                                   74
double(N) when is_number(N) ->
  N * 2;
double(N) when is_list(N) ->
  N ++ N.




                                 75
process(quot;/customerquot; ++ QString) ->
  customer(QString);




                                     76
process(quot;/customerquot; ++ QString) ->
  customer(QString);
process(quot;/employeequot; ++ QString) ->
  employee(QString);
process(Any) ->
  ok.




                                     77
Concurrent
programming


              78
Shared state



               79
Message passing



                  80
81
spawn(Fun)




             82
Pid = spawn(Fun)




                   83
Pid ! {lookup, {name, quot;Carlquot;}}




                                 84
receive
  {lookup, Query} ->
     query(Query)
end




                       85
receive
  {lookup, Query} ->
     query(Query);
  {update, Update} ->
     update(Update)
end




                        86
receive
  Any ->
    Any
end




           87
Pid ! Msg.
receiver ! Msg.
{receiver, 'notos@nugg.ad'} ! Msg.




                                     88
link(Pid)




            89
process_flag(trap_exit, true)




                               90
{'EXIT', From, Reason}




                         91
1> self().
<0.89.0>




             92
Distributed Erlang



                     93
spawn(Node, Fun)




                   94
Node = 'serv@flomac'.




                       95
node()




         96
nodes()




          97
net_adm:ping(Node)




                     98
Function Functions



                     99
lists



        100
map
foldl
filter


        101
lists:map(Fun, List)




                       102
L = [1,2,3,4,5],
L1 = lists:map(fun(E) ->
                 E * 2
               end, L).
[2,4,6,8,10]




                           103
lists:foldl(Fun, Acc, List)




                              104
L = [1,2,3,4,5],
L1 = lists:foldl(fun(E, Acc) ->
                 Acc + E
               end, L).
15




                                  105
lists:filter(Fun, List)




                         106
L = [1,2,3,4,5],
L1 = lists:filter(fun(E) ->
                 E rem 2 == 0
               end, L).
[2,4]




                                107
108
rpc:pmap({Module, Function},
     ExtraArgs,
     List2)




                               109
OTP



      110
111
Supervision Tree            Behaviours

             Applications

               Releases

          Up- & Downgrades


                                         112
113
{ch3, start_link, []}




                        114
init(_Args) ->
    {ok, {{one_for_one, 1, 60},
          [{ch3, {ch3, start_link, []},
             permanent, brutal_kill,
             worker, [ch3]}]
         }}.




                                          115
116
Behaviour



            117
Base Class

  Impl




             118
Behaviour

Callback




            119
Library



          120
kernel
erlang
                 code           file
   rpc
                  application   io
         inet
                error_logger



                                      121
stdlib
         math                                     dict
                       filename        sets
string
                                             lists   proplists
                dets             regexp
 random                                                  shell
                          array
            queue                         timer
                         gen_server

                                                                 122
123
Do stuff



           124
Unit Tests



             125
succeed() ->
    ok.

fail() ->
    throw(failed).

succeeding_test() ->
    succeed().

failing_test() ->
    fail().


                       126
succeeding_assert_test_() ->
    ?_assert(1 > 0).

failing_assert_test_() ->
    ?_assert(0 > 1).

succeeding_error_test_() ->
    ?_assertError(foo,
      erlang:error(foo)).

failing_error_test_() ->
    ?_assertError(foo,
      erlang:throw(foo)).

                               127
File IO



          128
{ok, Binary} =
  file:read_file(Filename)




                           129
{ok, Terms} =
  file:consult(Filename)




                          130
Macros



         131
?MODULE
?LINE


-define(OK, quot;200quot;).
?OK

-define(trace(A), ...)
?trace



                        132
Hello world



              133
$ sudo port install mochiweb
$ escript /opt/local/share/scripts/ 
  new_mochiweb.erl my 
  app$ cd myapp ; make
$ sh start-dev.sh

$ open localhost:8000




                                        134
135
136
536 Seiten
  Juli '07




             137
138
139
C. Florian Ebeling
florian.ebeling@gmail.com
 florian.ebeling@nugg.ad
        @febeling



                           140
Record



         141
-record(person, {name, age}).




                                142
.hrl



       143
new(Name, Age) ->
    #person{name=Name, age=Age}.




                                   144
name(P) ->
    P#person.name.




                     145
rename(P, NewName) ->
    P#person{name=Name}.




                           146
Where Next?



              147
400 Seiten
 März '09




             148
500 Seiten
 Mai '09




             149
ports
         edoc
      debugger
    erlang-mode
         distel
       type specs
        dialyzer
      mochiweb
         yaws
Lisp Flavoured Erlang
          Reia


                        150
OTP Behaviours



                 151
gen_server




             152
gen_fsm




          153
supervisor




             154
-module(sup).
-behaviour(supervisor).

-export([start_link/0]).
-export([init/1]).

start_link() ->
    supervisor:start_link(sup, []).

init(_Args) ->
...


                                      155
application




              156
filename:dirname(
  code:which(?MODULE))




                         157
11> {ok,File} =
  file:open(quot;PROJECTSquot;, [read]).
{ok,<0.92.0>}
13> io:get_line(File, []).
quot;Intro Erlang (am Mi., 17.10.08)nquot;
15> file:close(File).




                                      158

More Related Content

What's hot

Taint-based Dynamic Analysis (CoC Research Day 2009)
Taint-based Dynamic Analysis (CoC Research Day 2009)Taint-based Dynamic Analysis (CoC Research Day 2009)
Taint-based Dynamic Analysis (CoC Research Day 2009)
James Clause
 
Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6
fisher.w.y
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
riue
 

What's hot (20)

Prelude to halide_public
Prelude to halide_publicPrelude to halide_public
Prelude to halide_public
 
The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Jamming attack in wireless network
Jamming attack in wireless networkJamming attack in wireless network
Jamming attack in wireless network
 
R演習補講 (2腕バンディット問題を題材に)
R演習補講 (2腕バンディット問題を題材に)R演習補講 (2腕バンディット問題を題材に)
R演習補講 (2腕バンディット問題を題材に)
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
Investigating Python Wats
Investigating Python WatsInvestigating Python Wats
Investigating Python Wats
 
Program Language - Fall 2013
Program Language - Fall 2013 Program Language - Fall 2013
Program Language - Fall 2013
 
Elixir -Tolerância a Falhas para Adultos - GDG Campinas
Elixir  -Tolerância a Falhas para Adultos - GDG CampinasElixir  -Tolerância a Falhas para Adultos - GDG Campinas
Elixir -Tolerância a Falhas para Adultos - GDG Campinas
 
The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
 
Project hotel on hotel management fo
Project  hotel on hotel management foProject  hotel on hotel management fo
Project hotel on hotel management fo
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Ruby things
Ruby thingsRuby things
Ruby things
 
03
0303
03
 
Taint-based Dynamic Analysis (CoC Research Day 2009)
Taint-based Dynamic Analysis (CoC Research Day 2009)Taint-based Dynamic Analysis (CoC Research Day 2009)
Taint-based Dynamic Analysis (CoC Research Day 2009)
 
Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
CQL 实现
CQL 实现CQL 实现
CQL 实现
 

Similar to Erlang Introduction Bcberlin3

Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8
alish sha
 
Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8
alish sha
 

Similar to Erlang Introduction Bcberlin3 (20)

Introduction to Erlang
Introduction to ErlangIntroduction to Erlang
Introduction to Erlang
 
Stop Monkeys Fall
Stop Monkeys FallStop Monkeys Fall
Stop Monkeys Fall
 
Rkf
RkfRkf
Rkf
 
The Ring programming language version 1.8 book - Part 66 of 202
The Ring programming language version 1.8 book - Part 66 of 202The Ring programming language version 1.8 book - Part 66 of 202
The Ring programming language version 1.8 book - Part 66 of 202
 
The Ring programming language version 1.9 book - Part 69 of 210
The Ring programming language version 1.9 book - Part 69 of 210The Ring programming language version 1.9 book - Part 69 of 210
The Ring programming language version 1.9 book - Part 69 of 210
 
Groovy
GroovyGroovy
Groovy
 
The Ring programming language version 1.5.3 book - Part 69 of 184
The Ring programming language version 1.5.3 book - Part 69 of 184The Ring programming language version 1.5.3 book - Part 69 of 184
The Ring programming language version 1.5.3 book - Part 69 of 184
 
Functional Gradient Boosting based on Residual Network Perception
Functional Gradient Boosting based on Residual Network PerceptionFunctional Gradient Boosting based on Residual Network Perception
Functional Gradient Boosting based on Residual Network Perception
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
Vcs16
Vcs16Vcs16
Vcs16
 
TensorFlow 2: New Era of Developing Deep Learning Models
TensorFlow 2: New Era of Developing Deep Learning ModelsTensorFlow 2: New Era of Developing Deep Learning Models
TensorFlow 2: New Era of Developing Deep Learning Models
 
Linuxカーネルを読んで改めて知るプロセスとスレッドの違い
Linuxカーネルを読んで改めて知るプロセスとスレッドの違いLinuxカーネルを読んで改めて知るプロセスとスレッドの違い
Linuxカーネルを読んで改めて知るプロセスとスレッドの違い
 
The Ring programming language version 1.7 book - Part 64 of 196
The Ring programming language version 1.7 book - Part 64 of 196The Ring programming language version 1.7 book - Part 64 of 196
The Ring programming language version 1.7 book - Part 64 of 196
 
Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8
 
Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8
 
About Go
About GoAbout Go
About Go
 
Python And GIS - Beyond Modelbuilder And Pythonwin
Python And GIS - Beyond Modelbuilder And PythonwinPython And GIS - Beyond Modelbuilder And Pythonwin
Python And GIS - Beyond Modelbuilder And Pythonwin
 
Introduction To Lisp
Introduction To LispIntroduction To Lisp
Introduction To Lisp
 
pointers 1
pointers 1pointers 1
pointers 1
 
Lab loop
Lab loopLab loop
Lab loop
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 

Erlang Introduction Bcberlin3