SlideShare a Scribd company logo
Three sessions about Erlang




         Session 1
       Mohamed Samy
       February 2010
The need for parallel processing

  
      It has become prohibitive to raise the clock
      speeds of current CPUs any further.
  
      The next trend is to increase the number of CPU
      cores.
  
      In order to benefit from CPU upgrades, programs
      need to make the maximum possible use of
      parallelism.
  
      “The free lunch is over“
      (http://www.gotw.ca/publications/concurrency-
      ddj.htm)
Also, distributed processing :)

  
      Not only is the program running on multiple
      CPUs, but on multiple computers over the
      network.
  
      No shared memory, communication by
      message passing.
  
      Google's index, for example.
Current languages

 
     Both parallel and distributed applications have
     been written in traditional languages like C++,
     Java or C#, but...
 
     The problem is these languages depend too
     much on shared state.
 
     And they inherently make you think sequentially.
 
     Your programming language influences how you
     think about programs, not just how you write
     code.
Current languages
 
     The problem of shared mutable state (e.g
     global variables, object references...)
 
     Loop iterations run in sequence
 
     Assignment is very sequential
 Function calls have problems
     
         e.g: If function a( ) calls b( ), it keeps waiting for b( )
         to return before resuming operation.
 
     ‫فيه طرق للبرمجة غير كده أصل ؟‬
Erlang
 
     Created in 1986 by Joe Armstrong at Ericsson.
 
     Functional, dynamically typed, uses the actor
     model.
 
     Design goals:
     
         Concurrency, distribution, robustness, "soft" real
         time, hot code upgrades...and other goals.
 
     Used in Ericsson devices, Facebook chat,
     Amazon SimpleDB, now quickly growing.
 
     Now open source
Contents

 
     1st session: Sequential Erlang.

 
     2nd session: Concurrency and Actors.

 
     3rd session: A simple web application
Objectives of these sessions
  
      Introducing new concepts (Actor model,
      functional programming, immutable data).
  
      The importance of parallel programming.
  
      Stressing that there is much more to know
      about programming outside of traditional
      languages like C++, Java or C#.
      
          Not necessarily from Erlang only.
Erlang resources
 
     Download from
     http://www.erlang.org/download.html
 
     Lots and lots of documentation are included!
     
         Located in c:Program fileserl5.7.4docindex.html
     
         Especially look at "Getting started with
         Erlang" and "Erlang reference manual"
 
     Nice, searchable version of the
     documentation at www.erldocs.com
The Environment
    Commands always end in a dot: .
    help( ) to show all options
    cd(path) to change working directory
     Paths use a forward slash: "c:/examples/test1"
    c(file) to load & compile a file.
     e.g: c("example1"). % .erl extension is optional
    f( ) to forget all variable bindings
    Simple autocomplete with the <TAB> key.
    Lots and lots of documentation are included!
        c:Program fileserl5.7.4docindex.html
    Nice, searchable version of the documentation at www.erldocs.com
Data types
    Numbers: 12, -100, 15.55, $a
    Atoms: x, ayman, faculty_of_law
        Simple atoms cannot begin with a capital letter or have spaces,
         but single quotes can be used to bypass those rules: 'Samy',
         'calculus book'
    Tuples: { samy, 1979, cairo }, {13, 28}
    Lists: [ ], [1, 2, 3], [a, [b, c], {1, 2} ]
    Strings: "Hello world"
        This actually is the list [$H, $e, $l, $l, $o, $ ,$w, $o, $r, $l, $d ]
    All these data types are immutable
Data types and variables
 
     More information about these data types in the Erlang
     reference.
    Other important data types exists (e.g PID).
 
     A piece of data of any data type is called a term.
    Variables always start with a capital letter or underscore:
     X, Y, _Name, _name
 
     Variables can be bound to a value or still unbound
 
     Erlang has single assignment: a variable cannot be
     bound more than once.
Pattern matching
    A pattern is a term which may contain one or more variables.
    A term with no variables at all can be considered a pattern.
    Matching syntax is:
        Pattern = Term
    Each respective component of the term is compared,
     matching attempts to find the most general variable binding to
     make the match succeed.
    Quiz: what is the result of the following matches?
Pattern matching
 
     5=5.


 
     {Name, Age, _} = {“Osama”, 28, cairo }.


 
     [1,2] = {1, 2}.


 
     "hello" = "hello".


 
     "ABC" = [65, 66, 67].


    $a = a.
More pattern matching quizzes
 
     X=5.


 
     X=5. Y=X+1. Y=3+3.


 
     X=Y. Y=1.


 
     { X, Y } = { 5, 6 }


 
     { Y, Y } = { 5, 6 }


 (When testing these on Erlang; remember to use f( ) to reset
   variable bindings.)
Pattern matching on lists
  
      [ H | T ] = [1, 2, 3].
  
      [ H | T ] = [ ].
  
      [ H | T ] = [1, 2].
  
      [ H1, H2 | T ] = [1, 2, 3].
  
      [ H1, H2 | T ] = [1, 2].
  
      [A, B] ++ [ H| T] = "faculty".
  
      "Mustafa" ++ X = "Mustafa Kamel".
Some simple I/O
io:format(fmt_str, [arg0,arg1... ])

    Examples:
    
        io:format("The results are ~p and ~p", [15, 16]).
    
        io:format("Hello world ~n", [ ]).
    
        io:format("Hello world ~n").

    Codes:
    
        ~~ : The '~' mark (needs no argument)
    
        ~f : Format argument as floating point
    
        ~c : Format argument as a character.
    
        ~w : Format argument in standard syntax (i.e like terms in the language)
    
        ~p : Standard syntax for printing (e.g turns lists of printable characters into strings)
    
        ~n : newline character (doesn't need an argument).

    Much more detail in the documentation. Erlang has very rich formatting
    features.
More simple I/O
io:get_line(Prompt) -> Data | eof | {error,Reason}
     
         Gets a line from standard input as a string (includes the newline character).
io:read(Prompt) → {ok, Term} | eof | {error, ErrorInfo}
     
         Reads a term from standard input (user must include ending period).
io:fread(Prompt, Format) -> {ok, Terms} | eof | {error, What}
     
         Reads characters and returns a list of terms, parsed according to the specified format
         specification (different from that of io:format).

    Examples:
     
         io:read("Enter a point>").
     Enter a point>{13, 14}.
     {ok, {13, 14}}
     
         io:get_line("Enter your name>").
     Enter your name>Captain Majid
     “Captain Majidn"

    io:format( ), io:read( ) and all the other given i/o functions have additional parameters that can
    make them read from I/O devices like files...etc
Modules

          -module(addition).
          -export([add/2, add/3]).

          add(X, Y) -> X+Y.
          add(X, Y, Z) -> X+Y+Z.
          unused_func( ) -> io:format("unused!").
          % End of module definition.


    Erlang code is divided into modules.
 
     A module has attributes at the top (the begin with the dash character '-') and is followed by
     function declarations. Both attributes and declaration end with a dot '.'
 
     Exported function names must include its artiy (number of parameters).
 
     Two functions with the same name but different arities are different functions!
Functions
 
     add(A, B) → A+B.
        −   Return value is the function's expression
 
     add(A, B) →
     io:format(“now adding ~p and ~p~n", [A, B]),
     A+B.
        −   In case of multiple expressions, return value is the last
            one
Functions
 
     absolute(A) when A>0 → 1
     ;
 absolute(A) when A=0 → 0
     ;
 absolute(A) → -1
     .
 
     The expressions after when are called guard
     sequences. More about them in the Erlang language
     reference → Expressions → Guard sequences
Pattern matching in functions
  
      distance({X1 Y1}, {X2, Y2}) →
  Dx= X1-X2,
  Dy= Y1-Y2,
  math:sqrt(Dx*Dx + Dy*Dy).
  
      Tuples can be confusing (e.g is a tuple of two
      numbers a point, vector or age & salary?).
  
      We can use an atom in the beginning (the tag)
      to distinguish between kinds of data...
Pattern matching in functions
  
      distance({point, X1, Y1}, {point, X2, Y2}) →
  Dx= X1-X2,
  Dy= Y1-Y2,
  math:sqrt(Dx*Dx + Dy*Dy).

  
      example:distance({point, 0, 0}, {point, 100,
      100}).
Recursion
 factorial(0) ->1 ;
 factorial(N) -> N*factorial(N-1).

 
     Function calls, activation records, and why this
     works.
 
     We need this; we don't have loops !
 
     The space requirements of naïve recursion.
Recursion
 
     Tail calls vs. non tail calls.
 
     Tails calls are not only about recursion, but any
     function call.
 
     Tail call elimination. Now recursion can be as
     good as loops.
 
     In fact, it's can be compiled to jump instructions.
 
     Sometimes it can be much better than loops!
     
         Example: state machines
Next...

  
      Processes!
  
      Actors!
  
      Ping pong!
         −   Thursday, 11 February 2010.

More Related Content

PPTX
19. Data Structures and Algorithm Complexity
PPTX
Basic data types in python
PPTX
Python Data-Types
PPTX
Data types in python
PDF
Introduction to c++ ppt
PPTX
Scala 3 Is Coming: Martin Odersky Shares What To Know
PPTX
02. Data Types and variables
19. Data Structures and Algorithm Complexity
Basic data types in python
Python Data-Types
Data types in python
Introduction to c++ ppt
Scala 3 Is Coming: Martin Odersky Shares What To Know
02. Data Types and variables

What's hot (19)

PPT
Data Handling
PDF
Erlang, an overview
PPSX
DISE - Windows Based Application Development in Java
PPTX
Chapter 10 data handling
PDF
PPTX
Regular Expressions
PPTX
Regular Expressions in PHP
PPTX
An Introduction : Python
PDF
Python-01| Fundamentals
PPTX
Python basics
PDF
ITFT-Constants, variables and data types in java
PPTX
Values and Data types in python
PDF
Python lecture 06
PPTX
Types by Adform Research
PDF
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
PPTX
11 Unit 1 Chapter 02 Python Fundamentals
PDF
Python-03| Data types
PPTX
Python programming
PDF
Data file handling
Data Handling
Erlang, an overview
DISE - Windows Based Application Development in Java
Chapter 10 data handling
Regular Expressions
Regular Expressions in PHP
An Introduction : Python
Python-01| Fundamentals
Python basics
ITFT-Constants, variables and data types in java
Values and Data types in python
Python lecture 06
Types by Adform Research
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
11 Unit 1 Chapter 02 Python Fundamentals
Python-03| Data types
Python programming
Data file handling
Ad

Viewers also liked (8)

PDF
C# Summer course - Lecture 3
PDF
Spray intro
PDF
Erlang session2
PDF
Presentation skills for Graduation projects
PDF
C# Summer course - Lecture 4
PDF
Computational thinking in Egypt
PDF
Smalltalk, the dynamic language
PDF
Themes for graduation projects 2010
C# Summer course - Lecture 3
Spray intro
Erlang session2
Presentation skills for Graduation projects
C# Summer course - Lecture 4
Computational thinking in Egypt
Smalltalk, the dynamic language
Themes for graduation projects 2010
Ad

Similar to Erlang session1 (20)

PPT
C Tutorials
PPT
C# programming
PPTX
Python Workshop - Learn Python the Hard Way
PDF
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
PDF
Introduction to Erlang Part 1
PPTX
Introduction to Python , Overview
PDF
Erlang Message Passing Concurrency, For The Win
PDF
Pydiomatic
PDF
Python idiomatico
PDF
TI1220 Lecture 14: Domain-Specific Languages
PDF
Elixir
PPT
Scala Talk at FOSDEM 2009
PPT
C tutorial
PPT
C tutorial
PPT
C tutorial
PDF
C++primer
PPTX
PYTHON PPT.pptx python is very useful for day to day life
PDF
Reduce course notes class xii
PDF
A Brief Introduction to Scala for Java Developers
PDF
Miles Sabin Introduction To Scala For Java Developers
C Tutorials
C# programming
Python Workshop - Learn Python the Hard Way
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
Introduction to Erlang Part 1
Introduction to Python , Overview
Erlang Message Passing Concurrency, For The Win
Pydiomatic
Python idiomatico
TI1220 Lecture 14: Domain-Specific Languages
Elixir
Scala Talk at FOSDEM 2009
C tutorial
C tutorial
C tutorial
C++primer
PYTHON PPT.pptx python is very useful for day to day life
Reduce course notes class xii
A Brief Introduction to Scala for Java Developers
Miles Sabin Introduction To Scala For Java Developers

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Big Data Technologies - Introduction.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
KodekX | Application Modernization Development
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Modernizing your data center with Dell and AMD
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
cuic standard and advanced reporting.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Review of recent advances in non-invasive hemoglobin estimation
Encapsulation_ Review paper, used for researhc scholars
Unlocking AI with Model Context Protocol (MCP)
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Network Security Unit 5.pdf for BCA BBA.
Big Data Technologies - Introduction.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
KodekX | Application Modernization Development
Understanding_Digital_Forensics_Presentation.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Spectral efficient network and resource selection model in 5G networks
Modernizing your data center with Dell and AMD
Agricultural_Statistics_at_a_Glance_2022_0.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
CIFDAQ's Market Insight: SEC Turns Pro Crypto
cuic standard and advanced reporting.pdf
NewMind AI Monthly Chronicles - July 2025
Review of recent advances in non-invasive hemoglobin estimation

Erlang session1

  • 1. Three sessions about Erlang Session 1 Mohamed Samy February 2010
  • 2. The need for parallel processing  It has become prohibitive to raise the clock speeds of current CPUs any further.  The next trend is to increase the number of CPU cores.  In order to benefit from CPU upgrades, programs need to make the maximum possible use of parallelism.  “The free lunch is over“ (http://www.gotw.ca/publications/concurrency- ddj.htm)
  • 3. Also, distributed processing :)  Not only is the program running on multiple CPUs, but on multiple computers over the network.  No shared memory, communication by message passing.  Google's index, for example.
  • 4. Current languages  Both parallel and distributed applications have been written in traditional languages like C++, Java or C#, but...  The problem is these languages depend too much on shared state.  And they inherently make you think sequentially.  Your programming language influences how you think about programs, not just how you write code.
  • 5. Current languages  The problem of shared mutable state (e.g global variables, object references...)  Loop iterations run in sequence  Assignment is very sequential Function calls have problems  e.g: If function a( ) calls b( ), it keeps waiting for b( ) to return before resuming operation.  ‫فيه طرق للبرمجة غير كده أصل ؟‬
  • 6. Erlang  Created in 1986 by Joe Armstrong at Ericsson.  Functional, dynamically typed, uses the actor model.  Design goals:  Concurrency, distribution, robustness, "soft" real time, hot code upgrades...and other goals.  Used in Ericsson devices, Facebook chat, Amazon SimpleDB, now quickly growing.  Now open source
  • 7. Contents  1st session: Sequential Erlang.  2nd session: Concurrency and Actors.  3rd session: A simple web application
  • 8. Objectives of these sessions  Introducing new concepts (Actor model, functional programming, immutable data).  The importance of parallel programming.  Stressing that there is much more to know about programming outside of traditional languages like C++, Java or C#.  Not necessarily from Erlang only.
  • 9. Erlang resources  Download from http://www.erlang.org/download.html  Lots and lots of documentation are included!  Located in c:Program fileserl5.7.4docindex.html  Especially look at "Getting started with Erlang" and "Erlang reference manual"  Nice, searchable version of the documentation at www.erldocs.com
  • 10. The Environment  Commands always end in a dot: .  help( ) to show all options  cd(path) to change working directory Paths use a forward slash: "c:/examples/test1"  c(file) to load & compile a file. e.g: c("example1"). % .erl extension is optional  f( ) to forget all variable bindings  Simple autocomplete with the <TAB> key.  Lots and lots of documentation are included!  c:Program fileserl5.7.4docindex.html  Nice, searchable version of the documentation at www.erldocs.com
  • 11. Data types  Numbers: 12, -100, 15.55, $a  Atoms: x, ayman, faculty_of_law  Simple atoms cannot begin with a capital letter or have spaces, but single quotes can be used to bypass those rules: 'Samy', 'calculus book'  Tuples: { samy, 1979, cairo }, {13, 28}  Lists: [ ], [1, 2, 3], [a, [b, c], {1, 2} ]  Strings: "Hello world"  This actually is the list [$H, $e, $l, $l, $o, $ ,$w, $o, $r, $l, $d ]  All these data types are immutable
  • 12. Data types and variables  More information about these data types in the Erlang reference.  Other important data types exists (e.g PID).  A piece of data of any data type is called a term.  Variables always start with a capital letter or underscore: X, Y, _Name, _name  Variables can be bound to a value or still unbound  Erlang has single assignment: a variable cannot be bound more than once.
  • 13. Pattern matching  A pattern is a term which may contain one or more variables.  A term with no variables at all can be considered a pattern.  Matching syntax is:  Pattern = Term  Each respective component of the term is compared, matching attempts to find the most general variable binding to make the match succeed.  Quiz: what is the result of the following matches?
  • 14. Pattern matching  5=5.  {Name, Age, _} = {“Osama”, 28, cairo }.  [1,2] = {1, 2}.  "hello" = "hello".  "ABC" = [65, 66, 67].  $a = a.
  • 15. More pattern matching quizzes  X=5.  X=5. Y=X+1. Y=3+3.  X=Y. Y=1.  { X, Y } = { 5, 6 }  { Y, Y } = { 5, 6 } (When testing these on Erlang; remember to use f( ) to reset variable bindings.)
  • 16. Pattern matching on lists  [ H | T ] = [1, 2, 3].  [ H | T ] = [ ].  [ H | T ] = [1, 2].  [ H1, H2 | T ] = [1, 2, 3].  [ H1, H2 | T ] = [1, 2].  [A, B] ++ [ H| T] = "faculty".  "Mustafa" ++ X = "Mustafa Kamel".
  • 17. Some simple I/O io:format(fmt_str, [arg0,arg1... ])  Examples:  io:format("The results are ~p and ~p", [15, 16]).  io:format("Hello world ~n", [ ]).  io:format("Hello world ~n").  Codes:  ~~ : The '~' mark (needs no argument)  ~f : Format argument as floating point  ~c : Format argument as a character.  ~w : Format argument in standard syntax (i.e like terms in the language)  ~p : Standard syntax for printing (e.g turns lists of printable characters into strings)  ~n : newline character (doesn't need an argument).  Much more detail in the documentation. Erlang has very rich formatting features.
  • 18. More simple I/O io:get_line(Prompt) -> Data | eof | {error,Reason}  Gets a line from standard input as a string (includes the newline character). io:read(Prompt) → {ok, Term} | eof | {error, ErrorInfo}  Reads a term from standard input (user must include ending period). io:fread(Prompt, Format) -> {ok, Terms} | eof | {error, What}  Reads characters and returns a list of terms, parsed according to the specified format specification (different from that of io:format).  Examples:  io:read("Enter a point>"). Enter a point>{13, 14}. {ok, {13, 14}}  io:get_line("Enter your name>"). Enter your name>Captain Majid “Captain Majidn"  io:format( ), io:read( ) and all the other given i/o functions have additional parameters that can make them read from I/O devices like files...etc
  • 19. Modules -module(addition). -export([add/2, add/3]). add(X, Y) -> X+Y. add(X, Y, Z) -> X+Y+Z. unused_func( ) -> io:format("unused!"). % End of module definition.  Erlang code is divided into modules.  A module has attributes at the top (the begin with the dash character '-') and is followed by function declarations. Both attributes and declaration end with a dot '.'  Exported function names must include its artiy (number of parameters).  Two functions with the same name but different arities are different functions!
  • 20. Functions  add(A, B) → A+B. − Return value is the function's expression  add(A, B) → io:format(“now adding ~p and ~p~n", [A, B]), A+B. − In case of multiple expressions, return value is the last one
  • 21. Functions  absolute(A) when A>0 → 1 ; absolute(A) when A=0 → 0 ; absolute(A) → -1 .  The expressions after when are called guard sequences. More about them in the Erlang language reference → Expressions → Guard sequences
  • 22. Pattern matching in functions  distance({X1 Y1}, {X2, Y2}) → Dx= X1-X2, Dy= Y1-Y2, math:sqrt(Dx*Dx + Dy*Dy).  Tuples can be confusing (e.g is a tuple of two numbers a point, vector or age & salary?).  We can use an atom in the beginning (the tag) to distinguish between kinds of data...
  • 23. Pattern matching in functions  distance({point, X1, Y1}, {point, X2, Y2}) → Dx= X1-X2, Dy= Y1-Y2, math:sqrt(Dx*Dx + Dy*Dy).  example:distance({point, 0, 0}, {point, 100, 100}).
  • 24. Recursion factorial(0) ->1 ; factorial(N) -> N*factorial(N-1).  Function calls, activation records, and why this works.  We need this; we don't have loops !  The space requirements of naïve recursion.
  • 25. Recursion  Tail calls vs. non tail calls.  Tails calls are not only about recursion, but any function call.  Tail call elimination. Now recursion can be as good as loops.  In fact, it's can be compiled to jump instructions.  Sometimes it can be much better than loops!  Example: state machines
  • 26. Next...  Processes!  Actors!  Ping pong! − Thursday, 11 February 2010.