SlideShare uma empresa Scribd logo
1 de 26
Baixar para ler offline
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.

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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
 

Semelhante a Erlang session1

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

Semelhante a Erlang session1 (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
 
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
 
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
 
Java
JavaJava
Java
 

Último

Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServiceRenan Moreira de Oliveira
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIUdaiappa Ramachandran
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataSafe Software
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 

Último (20)

Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AI
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 

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.