SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
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.

Más contenido relacionado

La actualidad más candente

DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaRasan Samarasinghe
 
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board ExamsC++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Examshishamrizvi
 
Regular Expressions in PHP
Regular Expressions in PHPRegular Expressions in PHP
Regular Expressions in PHPAndrew Kandels
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : PythonRaghu Kumar
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| FundamentalsMohd Sajjad
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaAtul Sehdev
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in pythonJothi Thilaga P
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform ResearchVasil Remeniuk
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Ranel Padon
 
11 Unit 1 Chapter 02 Python Fundamentals
11  Unit 1 Chapter 02 Python Fundamentals11  Unit 1 Chapter 02 Python Fundamentals
11 Unit 1 Chapter 02 Python FundamentalsPraveen M Jigajinni
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data typesMohd Sajjad
 
Python programming
Python programmingPython programming
Python programmingsaroja20
 

La actualidad más candente (20)

Data Handling
Data HandlingData Handling
Data Handling
 
Erlang, an overview
Erlang, an overviewErlang, an overview
Erlang, an overview
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
Chapter 10 data handling
Chapter 10 data handlingChapter 10 data handling
Chapter 10 data handling
 
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board ExamsC++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
 
3.5
3.53.5
3.5
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
Regular Expressions in PHP
Regular Expressions in PHPRegular Expressions in PHP
Regular Expressions in PHP
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Python basics
Python basicsPython basics
Python basics
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in java
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
Python lecture 06
Python lecture 06Python lecture 06
Python lecture 06
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
 
11 Unit 1 Chapter 02 Python Fundamentals
11  Unit 1 Chapter 02 Python Fundamentals11  Unit 1 Chapter 02 Python Fundamentals
11 Unit 1 Chapter 02 Python Fundamentals
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
 
Python programming
Python programmingPython programming
Python programming
 
Data file handling
Data file handlingData file handling
Data file handling
 

Destacado

C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3mohamedsamyali
 
Presentation skills for Graduation projects
Presentation skills for Graduation projectsPresentation skills for Graduation projects
Presentation skills for Graduation projectsmohamedsamyali
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4mohamedsamyali
 
Computational thinking in Egypt
Computational thinking in EgyptComputational thinking in Egypt
Computational thinking in Egyptmohamedsamyali
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic languagemohamedsamyali
 
Themes for graduation projects 2010
Themes for graduation projects   2010Themes for graduation projects   2010
Themes for graduation projects 2010mohamedsamyali
 

Destacado (8)

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

Similar a Erlang Concurrency and Actors

Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...Hamidreza Soleimani
 
Introduction to Erlang Part 1
Introduction to Erlang Part 1Introduction to Erlang Part 1
Introduction to Erlang Part 1Dmitry Zinoviev
 
Introduction to Python , Overview
Introduction to Python , OverviewIntroduction to Python , Overview
Introduction to Python , OverviewNB Veeresh
 
Erlang Message Passing Concurrency, For The Win
Erlang  Message  Passing  Concurrency,  For  The  WinErlang  Message  Passing  Concurrency,  For  The  Win
Erlang Message Passing Concurrency, For The Winl xf
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesEelco Visser
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xiiSyed Zaid Irshad
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersMiles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 

Similar a Erlang Concurrency and Actors (20)

C Tutorials
C TutorialsC Tutorials
C Tutorials
 
C# programming
C# programming C# programming
C# programming
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
 
Introduction to Erlang Part 1
Introduction to Erlang Part 1Introduction to Erlang Part 1
Introduction to Erlang Part 1
 
Introduction to Python , Overview
Introduction to Python , OverviewIntroduction to Python , Overview
Introduction to Python , Overview
 
Erlang Message Passing Concurrency, For The Win
Erlang  Message  Passing  Concurrency,  For  The  WinErlang  Message  Passing  Concurrency,  For  The  Win
Erlang Message Passing Concurrency, For The Win
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific Languages
 
Elixir
ElixirElixir
Elixir
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C++primer
C++primerC++primer
C++primer
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Java
JavaJava
Java
 

Último

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Último (20)

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 

Erlang Concurrency and Actors

  • 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.