• Nem Talált Eredményt

Industrial Functional Programming Languages

N/A
N/A
Protected

Academic year: 2022

Ossza meg "Industrial Functional Programming Languages"

Copied!
118
0
0

Teljes szövegt

(1)

Industrial Functional Programming Languages

Melinda Tóth, István Bozó

(2)

Industrial Functional Programming Languages

Melinda Tóth, István Bozó Publication date 2014

Copyright © 2014 Melinda Tóth, István Bozó

Supported by TÁMOP-4.1.2.A/1-11/1-2011-0052.

(3)

Table of Contents

1. Lecture 1 ... 1

1. Introduction ... 1

1.1. Functional Programming ... 1

1.2. Functional Programming Languages ... 1

1.3. Factorial ... 1

1.4. Factorial Calculation in Erlang ... 1

1.5. Properties ... 1

1.6. Properties ... 2

1.7. Properties ... 2

1.8. Properties ... 2

1.9. Properties ... 2

1.10. Properties ... 2

1.11. Properties ... 3

1.12. Properties ... 3

1.13. Properties ... 3

1.14. Properties ... 3

1.15. Properties ... 3

2. Erlang ... 3

2.1. History ... 3

2.2. Erlang – Properties ... 4

2.3. Erlang – Ericsson Language ... 4

2.4. When To Use Erlang? ... 5

2.5. Who Uses Erlang? ... 5

2.6. Literature and materials to use ... 5

2. Lecture 2 ... 6

1. The Erlang Virtual Machine ... 6

1.1. Erlang VM ... 6

1.2. Erlang Evaluation ... 6

1.3. Erlang shell ... 6

1.4. Useful Shell Commands ... 6

2. Erlang Terms ... 7

2.1. Types – Terms ... 7

2.2. Numbers ... 7

2.3. Binaries & Bitstrings ... 7

2.4. Atoms ... 7

2.5. Tuple ... 8

2.6. List ... 8

2.7. Unique identifiers and Funs ... 8

2.8. Terms ... 8

3. Comparison ... 9

3.1. Comparison Of Types&Terms ... 9

3. Lecture 3 ... 10

1. Variables ... 10

1.1. Variables ... 10

2. Pattern Matching ... 10

2.1. Pattern Matching ... 10

3. Emacs usage ... 10

3.1. Erlang mode in Emacs ... 10

3.2. Modules ... 10

3.3. Elements of the module ... 10

3.4. Attributes ... 11

3.5. An example module ... 11

3.6. Compiling And Loading Modules ... 11

3.7. Functions – ModName:FunName/Arity ... 11

3.8. Simple functions ... 12

3.9. Sequence of expressions ... 12

(4)

Industrial Functional Programming Languages

4. Lecture 4 ... 13

1. Important Functions ... 13

1.1. Built In Functions (BIF) ... 13

2. Documentations ... 13

2.1. Documentation And STDLIB ... 13

3. Recursive Functions ... 13

3.1. Recursion ... 13

3.2. Primitive Recursion ... 13

3.3. Tail-Recursion ... 14

3.4. Tail-Recurssive Fibonacci ... 14

4. Lists ... 14

4.1. Lists ... 14

4.2. List Comprehension ... 14

4.3. Square of even numbers ... 14

4.4. QuickSort ... 15

4.5. Primitive Recursion ... 15

4.6. Tail-Recursion ... 15

5. Lecture 5 ... 16

1. Guards ... 16

1.1. Guard Expressions ... 16

1.2. Guard Expressions ... 16

2. Conditional Evaluation ... 16

2.1. Case Expression ... 16

2.2. Case Expression ... 16

2.3. If Expression ... 17

2.4. If Expression ... 17

3. Fun Expressions ... 17

3.1. Explicit Fun Expressions ... 17

3.2. Explicit Fun Expressions ... 18

3.3. Implicit Fun Expressions ... 18

3.4. Implicit Fun Expressions ... 18

4. Dynamic Function Calls ... 18

4.1. Dynamic constructs ... 18

4.2. Dynamic constructs ... 18

6. Lecture 6 ... 20

1. Run-time Errors ... 20

1.1. Types of Run-time Errors ... 20

1.2. Types of Run-time Errors ... 20

1.3. Types of Run-time Errors ... 20

1.4. Trapping Run-time Errors ... 21

1.5. Trapping Run-time Errors ... 21

1.6. Pattern Matching on the value ... 22

1.7. Trapping Run-time Errors ... 22

1.8. Trapping Run-time Errors ... 22

1.9. Raising Exeptions ... 22

2. Records ... 22

2.1. Records ... 23

2.2. Records ... 23

2.3. Records ... 23

3. Lazyness ... 24

3.1. “Lazy” list ... 24

7. Lecture 7 ... 25

1. Macros ... 25

1.1. Macros ... 25

1.2. Macros ... 25

1.3. Conditional Macros ... 25

1.4. Macros ... 25

1.5. Crosscutting Macros ... 25

1.6. Conditional Macros ... 26

(5)

2.1. Bitstring and binary ... 26

2.2. Binary Comprehensions ... 26

3. I/O operations ... 26

3.1. Input and Output ... 26

3.2. Formatting ... 27

3.3. File handling ... 27

3.4. File handling ... 27

3.5. File handling ... 28

8. Lecture 8 ... 29

1. Concurrency/Parallelism ... 29

1.1. Basics ... 29

1.2. Basics ... 29

1.3. Basics ... 29

2. Processes and Messages ... 29

2.1. Erlang Processes ... 29

2.2. Message Sending ... 30

2.3. Examples ... 30

2.4. Process links and error handling ... 30

2.5. Receive Expressions ... 30

2.6. Timeout ... 30

2.7. Example ... 31

9. Lecture 9 ... 32

1. Process Registration ... 32

1.1. Registering Processes ... 32

1.2. Message Sending ... 32

2. Disributed Erlang ... 32

2.1. Distributed Erlang Nodes ... 32

2.2. Distributed Erlang Nodes ... 32

2.3. Distributed Erlang Nodes ... 33

2.4. Distributed Erlang Nodes ... 33

2.5. Example Connection ... 33

2.6. Example Connection ... 33

2.7. Distributed Ping-Pong ... 34

2.8. Tools to Use ... 34

10. Lecture 10 ... 35

1. Server Skeleton ... 35

1.1. Servers step-by-step ... 35

1.2. Starting the server ... 35

1.3. Handling requests ... 35

1.4. Stopping the server ... 35

1.5. Server Skeleton ... 36

2. Software Upgrade ... 36

2.1. Software Upgrade ... 36

2.2. Code Server ... 36

3. ETS/DETS ... 36

3.1. ETS ... 37

3.2. ETS operations ... 37

3.3. ETS Advanced Search ... 37

3.4. DETS ... 37

3.5. Tool to Use ... 37

11. Lecture 11 ... 38

1. Erlang OTP ... 38

1.1. OTP ... 38

2. OTP behaviours ... 38

2.1. OTP behaviours ... 38

2.2. Example – client-server ... 38

2.3. OTP behaviours ... 39

2.4. Pro & con ... 39

2.5. Generic Servers ... 39

2.6. Generic Servers ... 39

(6)

Industrial Functional Programming Languages

2.7. Starting a Server ... 39

2.8. Passing Messages ... 40

2.9. Stopping the Server ... 40

2.10. -behaviour(gen_server) ... 40

12. Lecture 12 ... 41

1. Supervisors ... 41

1.1. Supervisors ... 41

1.2. Supervisors ... 41

1.3. Supervisors: ChildSpecList ... 41

1.4. Supervisors: Dynamic children ... 41

2. Applications ... 41

2.1. Applications ... 42

2.2. Applications Description File ... 42

2.3. Applications Behaviour ... 42

2.4. Starting and Stopping the Application ... 42

13. Lecture 13 ... 43

1. NIF ... 43

1.1. NIF – Native Implemented Function ... 43

1.2. Specify Load Action and Load NIF ... 43

1.3. Implement Dummy Functions ... 43

1.4. Erlang file ... 43

1.5. C file ... 43

1.6. Define the Functions to Load ... 44

1.7. Specify Mappings ... 44

2. Port and Port driver ... 44

2.1. Port ... 44

2.2. Port ... 45

2.3. Port Example: Erlang File ... 45

2.4. Port Example: C File ... 45

2.5. Port Example: C File ... 46

2.6. Port Example: C File ... 46

2.7. Port Example: C File ... 46

2.8. Compiling and Run ... 47

2.9. Connection with other languages ... 47

14. Lecture 14 ... 48

1. Databases ... 48

1.1. Database support ... 48

2. Mnesia ... 48

2.1. (A)Mnesia ... 48

2.2. Mnesia ... 48

3. Web-servers ... 48

3.1. Web-servers ... 48

3.2. YAWS configuration, yaws.conf ... 49

3.3. index.yaws ... 49

3.4. greetings.yaws ... 49

3.5. erlcode.erl ... 50

15. Practice 1 ... 51

1. Erlang Shell ... 51

1.1. Erlang Shell Basic Commands ... 51

1.2. Exercises ... 51

1.3. Exercises – Numbers ... 51

1.4. Operators On Numbers ... 51

1.5. Exercises – Operators On Numbers ... 51

1.6. Atoms And Booleans ... 52

1.7. Exercises – Atoms ... 52

1.8. Boolean Operators And Comparisons ... 52

1.9. Exercises – Boolean Operators And Comparisons ... 52

1.10. Lists And Strings ... 53

1.11. Exercises – Lists And Strings ... 53

(7)

1.13. Exercises – Variables ... 53

1.14. Tuple ... 54

1.15. Exercises – Tuple ... 54

1.16. Function Application ... 54

1.17. Exercises – Function Application ... 54

16. Practice 2 ... 55

1. Modules and Functions ... 55

1.1. Erlang Modules ... 55

1.2. Exercises – Erlang Module ... 55

1.3. Function definitions ... 55

2. Pattern Matching ... 55

2.1. Pattern Matching ... 55

2.2. Exercises – Pattern Matching ... 56

2.3. Guard Expression ... 56

2.4. Exercises – Function definitions ... 56

2.5. Exercises – Function definitions ... 56

3. Recursion ... 57

3.1. Recursion ... 57

3.2. Exercises – Recursion ... 57

3.3. Exercises – Recursion ... 57

3.4. Exercises – Recursion ... 58

17. Practice 3 ... 59

1. List Comprehensions ... 59

1.1. List Comprehensions ... 59

1.2. Exercises – List Comprehensions ... 59

1.3. Exercises – List Comprehensions ... 59

1.4. Exercises – List Comprehensions ... 60

1.5. Exercises – List Comprehensions ... 60

1.6. Exercises – List Comprehensions ... 60

18. Practice 4 ... 62

1. Lambda expressions ... 62

1.1. Funexpresisons/Lambda expressions ... 62

1.2. Exercises ... 62

2. Examples ... 62

2.1. Perfect Numbers ... 62

2.2. Perfect Numbers ... 62

2.3. Perfect Numbers ... 63

2.4. Perfect Numbers ... 63

2.5. Perfect Numbers ... 63

2.6. Perfect Numbers ... 63

2.7. Perfect Numbers ... 63

2.8. Perfect Numbers ... 64

2.9. Perfect Numbers ... 64

19. Practice 5 ... 65

1. Raising Errors ... 65

1.1. Errors ... 65

1.2. Errors ... 65

2. Handling Errors ... 65

2.1. Handling Errors ... 66

2.2. Handling Errors ... 66

3. Lazy Evaluation ... 66

3.1. Lazy Generation ... 66

3.2. Lazy Generation ... 66

20. Practice 6 ... 68

1. Records ... 68

1.1. Defining the Employee Registry System ... 68

1.2. Defining the Employee Registry System ... 68

1.3. Defining the Employee Registry System ... 68

1.4. Defining the Employee Registry System ... 69

1.5. Defining the Employee Registry System ... 69

(8)

Industrial Functional Programming Languages

1.6. Defining the Employee Registry System ... 69

2. Macros ... 69

2.1. Defining Macros ... 69

2.2. Defining Macros ... 70

2.3. Defining Macros ... 70

2.4. Conditional Compiling ... 70

21. Practice 7 ... 71

1. I/O operations ... 71

1.1. Reading from the standard input ... 71

1.2. Reading atoms ... 71

1.3. Evaluating dynamic-functions ... 71

1.4. Reading the information ... 71

1.5. Evaluation ... 72

2. Binary & Bitstring ... 72

2.1. Reading Binaries/Bitstrings ... 72

2.2. Reading the information ... 73

22. Practice 8 ... 74

1. Using the Communication Primitives ... 74

1.1. Flush ... 74

1.2. Sleep ... 74

1.3. Alarm ... 74

1.4. Alarm ... 74

2. Writing Parallel/Concurrent Programs ... 75

2.1. FORK ... 75

2.2. FORK ... 75

2.3. FORK ... 75

2.4. Pipeline ... 75

2.5. Pipeline initialization ... 75

2.6. Pipeline Data Sending and Calculation ... 76

23. Practice 9 ... 77

1. Token Ring ... 77

1.1. Token Ring ... 77

1.2. Starting the Processes ... 77

1.3. Sending The ok Message ... 77

1.4. Token Ring Module ... 77

1.5. Measure Evaluation Time ... 77

2. Improved Token Ring ... 78

2.1. Token Ring ... 78

2.2. Starting the Processes ... 78

2.3. Sending the Message ... 78

2.4. Token Ring ... 78

2.5. Token Ring ... 79

2.6. Further Improvements ... 79

24. Practice 10 ... 80

1. Servers ... 80

1.1. Server Skeleton ... 80

2. Natural Number Generator ... 80

2.1. NNG ... 80

2.2. Starting the Server ... 80

2.3. Waiting for requests ... 81

2.4. Handling requests ... 81

2.5. Stopping the server ... 81

2.6. Server Interface ... 81

2.7. NNG Server ... 82

2.8. NNG Server ... 82

2.9. Run the Server ... 82

3. Distributed Natgen Server ... 83

3.1. Distributed NNG ... 83

3.2. Distributed message sending ... 83

(9)

3.4. Setting ... 83

3.5. Run the Server ... 83

3.6. Further Improvements ... 84

25. Practice 11 ... 85

1. Global Process Registration ... 85

1.1. Global ... 85

2. Global Natural Number Generator ... 85

2.1. Global NNG ... 85

2.2. Starting the Server ... 85

2.3. Waiting for requests ... 85

2.4. Handling requests ... 86

2.5. Stopping the server ... 86

2.6. Server Interface ... 86

2.7. Global NNG Server ... 86

2.8. Setting ... 87

2.9. Setting ... 87

2.10. Run the Server ... 87

3. Hot Code Loading ... 87

3.1. Code Upgrade ... 87

3.2. Adding qualified function calls: ?MODULE:loop ... 88

3.3. Global NNG ... 88

3.4. Run the Server ... 88

3.5. Changing the source ... 88

3.6. Recompile and Try ... 89

3.7. Further Improvements ... 89

26. Practice 12 ... 90

1. Client-Server Applications ... 90

1.1. Chat Server ... 90

1.2. Chat Client ... 90

2. Implementation of a Chat Server ... 90

2.1. Starting the Server ... 90

2.2. Handling Client Failour and Unwanted Messages ... 90

2.3. Waiting for Client Requests ... 91

2.4. Handling Connections ... 91

2.5. Handling Chat Messages ... 91

2.6. Handling Disconnection ... 92

2.7. Handling Group Joins ... 92

2.8. Stopping the server and Dump Clients ... 92

2.9. Server Interface ... 93

2.10. Chat Server ... 93

2.11. Chat Server ... 93

2.12. Chat Server ... 94

2.13. Chat Server ... 94

2.14. Chat Server ... 95

2.15. Setting ... 95

2.16. Setting ... 95

2.17. Run the Server ... 96

2.18. Further Improvements ... 96

27. Practice 13 ... 97

1. Client-Server Applications ... 97

1.1. Chat Server ... 97

1.2. Chat Client ... 97

2. Implementation of a Chat Client ... 97

2.1. Starting the Client and Connect to the Server ... 97

2.2. Wait for Server Messages ... 97

2.3. Waiting for User Input ... 98

2.4. Handling User Input ... 98

2.5. Handling User Input ... 98

2.6. Interfacing with the Server ... 98

2.7. Chat Client ... 99

(10)

Industrial Functional Programming Languages

2.8. Chat Client ... 99

2.9. Chat Client ... 100

2.10. Setting ... 100

2.11. Setting ... 100

2.12. Run the Server ... 100

2.13. Further Improvements ... 101

28. Practice 14 ... 102

1. Generic Client-Server Applications ... 102

1.1. Chat Server ... 102

1.2. Chat Client ... 102

1.3. What is generic or specific? ... 102

2. Using gen_servers ... 102

2.1. Starting the Server ... 103

2.2. Waiting for Client Requests ... 103

2.3. Handling Connections ... 103

2.4. Handling Chat Messages ... 103

2.5. Handling Disconnection ... 103

2.6. Handling Group Joins ... 104

2.7. Handling Client Failour and Unwanted Messages ... 104

2.8. Stopping the server and Dump Clients ... 104

2.9. Handling Upgrades ... 105

2.10. Generic Chat Server ... 105

2.11. Generic Chat Server ... 105

2.12. Generic Chat Server ... 105

2.13. Generic Chat Server ... 106

2.14. Generic Chat Server ... 106

2.15. Generic Chat Server ... 106

2.16. Modifying the Client ... 107

2.17. Modifying the Client ... 107

2.18. Modifying the Client ... 107

2.19. Setting ... 108

2.20. Setting ... 108

2.21. Run the Server ... 108

(11)

Chapter 1. Lecture 1

1. Introduction

1.1. Functional Programming

• The topmost level is a set of modules

• The module is a set of declaration (type, class, function)

• Initial statement

• Evaluation

• Based on mathematical model (Lambda Calculus)

• Turing complete

1.2. Functional Programming Languages

• Lisp,

• Haskell, Clean,

• Scheme, SML,

Erlang, Scala,

• F#, OCaml,

• Miranda, Closure,

• Agda, Epigram,

• etc.

1.3. Factorial

How can we calculate the factorial of a number?

• 0! = 1

• N! = N*(N-1)!

1.4. Factorial Calculation in Erlang

fact(0) -> 1;

0! = 1

fact(N) -> N * fact(N-1).

N! = N * (N-1)!

1.5. Properties

• Referential transparency

• (Static typing)

(12)

Lecture 1

• Higher-order functions

• (Currying)

• Recursion

• Strict(/lazy) evaluation

• List comprehensions

• Pattern matching

• (“Offset rule”)

• IO model

1.6. Properties

(Static typing)

-spec(fact(pos_int())->pos_int()) fact(-3.5)

1.7. Properties

Higher-order functions

• Mathematical example: differential calculus m_fun(Fun, A, B) -> Fun(A, B).

m_fun(fun add/2, A, B) m_fun(fun mul/2, A, B)

1.8. Properties

(Currying)

add(A, B) = A + B.

add(1) = fun(B) -> 1 + B end = inc(B).

inc(3) = 4.

add(1)(3) = 4.

1.9. Properties

Recursion fact(0) -> 1;

fact(N) -> N * fact(N-1).

1.10. Properties

Strict(/lazy) evaluation

• Calculate the first three natural number!

take([1..])

(13)

1.11. Properties

List Comprehensions (Zermelo-Frankel set-expressions)

• Calculate the square of the first two hundred even natural number!

{x^2 | x in N, x < 200, 2 | x}

[x*x | x <- [1..], x < 200, x mod 2 == 0]

[X*X || X <- lists:seq(1,200), X rem 2 == 0]

1.12. Properties

Pattern Matching [Head | Tail ] = [1,2,3,4,5,6]

Head = 1

Tail = [2,3,4,5,6]

{X, Y, Z} = {1,2,3}

X = 1 Y = 2 Z = 3

1.13. Properties

(Offset rule)

fact 0 = 1

" "fact x = x * fact x-1

fact 0 = 1

fact x = x * fact x-1

1.14. Properties

Referential Transparency

fact(6) == 720 ...

fact(6) == 720

1.15. Properties

Purity/Side-effects

2. Erlang

2.1. History

(14)

Lecture 1

• 1982 - 1986 – Experiments with different programming languages

• 1987 – First experiments with Erlang

• 1988 - 1990 – Experiences with Erlang in telecom world

• 1993 – Distributed programming / First Erlang book (The BOOK)

• 1996 – OTP R1

• 1998 – Released as Open Source

• 2005 – R11 multicore

2.2. Erlang – Properties

• Declarative – Functional programming language, high level of abstraction

• Dynamically typed

• Concurrency – explicit concurrency, LWP

• Soft real-time characteristics

• Robustness – supervision trees

• Distribution – transparent, explicit, network

• Openness, external interfaces – “ports”

• Portability – Unix, Win., ... , heterogeneous network

• SMP Support – multicore

• “Hot code loading”

2.3. Erlang – Ericsson Language

(15)

• Danish mathematician

• Erlang formula

• erlang – unit of load on telephone circuits

2.4. When To Use Erlang?

• Complex, continuously operating, scalable, maintainable, distributed

• Rapid and efficient development

• Fault-tolerant (software, hardware) systems

• Hot-code loading

2.5. Who Uses Erlang?

• Ericsson – telecommunication (AXD301 ATM switch), simulation, testing, 3G, GPRS

• Amazon – Simple DB (DBMS)

• Yahoo – Online bookmarks service

• Facebook – chat server

• T-Mobile – SMS gateway

• Motorola – call processing

• MochiWeb – http server

• CouchDb – document database server (multicore, multiserver clusters)

• YAWS – Yet Another Web Server

• Wings3D – 3D modeling

• and many other...

2.6. Literature and materials to use

erlang.org

• Erlang Programming: A Concurrent Approach to Software Development by Francesco Cesarini, Simon Thompson. O‟Reilly Media

• Programming Erlang: Software for a Concurrent World by Joe Armstrong. The Pragmatic Bookshelf

• Learn You Some Erlang for Great Good! A Beginner‟s Guide by Fred Hebert. No Starch Press.

erlang-factory.org

(16)

Chapter 2. Lecture 2

1. The Erlang Virtual Machine

1.1. Erlang VM

• The Prolog interpreter – 1986

• JAM - Joe‟s Abstract Machine – 1989

• BEAM - (Bogdan‟s) Björn‟s Erlang Abstract Machine

1.2. Erlang Evaluation

• Erlang emulator

• Erlang code compiled to bytecode

• Loaded to the VM

• Evaluated by the VM

• Elang shell: read-eval-print loop

1.3. Erlang shell

erl, erl.exe, werl.exe

1 + 2. "apple".

q(). init:stop().

• BREAK menu: Ctrl-C / Ctrl-Break

• User Switch Command: Ctrl-G – job contorller

1.4. Useful Shell Commands

help()

h()

i()

memory()

c(ModName)

ls(), ls(Dir)

b()

f(), f(X)

e(Number),e(-1)

v()

(17)

m(ModName), module_name:module_info()

pwd(), cd(Path)

2. Erlang Terms

2.1. Types – Terms

• Numbers (Integer, Float)

• Binaries/Bitstrings

• Atoms

• Tuples

• Lists (Strings)

• Unique identifiers: pids, ports, references

• Funs

2.2. Numbers

• Integer – 10, 2#10101, 36#PQ3, $w

• Floats – 0.01, 17.2, 11.12E-10

• Arithmetic operators: +, -, *, /, div, rem

math module -> sqrt, pow

N bsl K, N bsr K

band, bor, bxor, bnot

2.3. Binaries & Bitstrings

• Binary: sequence of bytes

• Bitstring: sequence of bit

<<>>, << 0,1,2,3>>

<< "hello", 0, "dummy">>

2.4. Atoms

• String constant

• Atom – lower + letter + digit + @ + _

’An atom’, an_atom1

• %% Boolean – true, false

ok & undefined

• Maximum length: 255 characters

• Maximum number of atoms 1048576 (default)

(18)

Lecture 2

2.5. Tuple

• Fixed number of elements (n-tuple)

• Tuple – {...}

{foo, bar, {1,2}, "gazonk"}

{}

• Tagged tuple: {int, 42}, {pos, 23, 43}

element(n, Tuple)

2.6. List

• Data structure with dynamic length

• List – [...], String – "..."

[], "", [1,23, {foo, 2}, [bar, [gazonk]]]

[1 | []], [1 | [2]], [1,2,3 | [4,5]]

[1,2] ++ [3,4,5]

[97,98,99,100] == "abcd" == [$a,$b,$c,$d]

• ??? [0 | v(Num)] ???

• Proper & improper lists

2.7. Unique identifiers and Funs

• Pid – < 0.4.2>

• Port – #Port<0.472>

• Reference – #Ref<0.0.0.42>

• Fun – #Fun<...>

2.8. Terms

• Integer – 10 (binary, octal, hexadecimal etc.)

• Floats – 17.2, 11.12E-10

• Binaries and Bitstrings

• Atom – lower + letter + digit + @ + _

• %% Boolean – true, false

• Tuple – {...}

• List – [...] , String – "..."

• Unique identifiers: pid, port, reference

• Fun

(19)

3. Comparison

3.1. Comparison Of Types&Terms

number < atom < fun < port < pid < tuple < list < binary

< >

=< >=

/= ==

=:= =/=

(20)

Chapter 3. Lecture 3

1. Variables

1.1. Variables

• Start with an Upper Case Letter or underscore character

• Single assignment

• There is no need to declare variables

• Passed by value

• Variables are local to a function clause

• ??? Global variable ???

2. Pattern Matching

2.1. Pattern Matching

• Controlling the execution flow

• Assigning values to variables

• Extracting values from compound data structures

X = 2

{A, A, X} = {1, 1,3}

[Head | Tail] = [1,2,3]

3. Emacs usage

3.1. Erlang mode in Emacs

(add-to-list ‟exec-path "/path_to_erlang/bin")

(add-to-list ‟load-path "/path_to_erlang/lib/tools-2.6.5/emacs") (require ‟erlang-start)

3.2. Modules

• Name of the module is an atom

• File extension: “.erl”

-module(module_name).

• Sequence of forms (attributes and function declarations)

• Every form is terminated by a period (.)

3.3. Elements of the module

(21)

• Function definitions

• Attributes – module, export, import, include, compile, behaviour, user_defined

• Macros

• Records

• Header files

• Comment - %

3.4. Attributes

-module(module_name).

-export([fun1/0, fun2/1]).

-import(lists, [max/1, map/2]).

-include("file”).

-compile(export_all).

-author(’TothMelinda’).

3.5. An example module

-module(amod).

-export([f/0]).

-author(melinda).

-date(’20.12.2012.’).

f()->

ok.

3.6. Compiling And Loading Modules

c(amod)

l(amod)

code:get_path(), code:add_patha/1

• Editing the .erlang file

erlc amod.erl

amod:f().

3.7. Functions – ModName:FunName/Arity

name(Arg11, ..., Arg1N) [when Guard1] ->

ExprList1;

name(Arg21, ..., Arg2N) [when Guard2] ->

ExprList2;

...

name(ArgM1, ..., ArgMN) [when GuardM]->

ExprListM.

(22)

Lecture 3

Exprlist ::= Expr1, Expr2, ... ExprK.

modname:funname(Par1, ..., Parn) funname(Par1, ..., Parn)

3.8. Simple functions

fact(0) -> 1;

fact(N) when N>0 ->

N * fact(N-1).

fib(1) -> 1;

fib(2) -> 1;

fib(N) when N>2 ->

fib(N-1)+fib(N-2).

3.9. Sequence of expressions

fib(1) -> 1;

fib(2) -> 1;

fib(N) when N>2 ->

N1 = fib(N-1), N2 = fib(N-2), Result = N1 + N2, Result.

(23)

Chapter 4. Lecture 4

1. Important Functions

1.1. Built In Functions (BIF)

• Implemented in C

• Interface in module “erlang”

• Low level operations, performance

• Functions with side-effect

• etc.

hd/1, tl/1, length/1

size/1, element/2, setelement/2

list_to_tuple/1, ineteger_to_list/1, ...

is_atom/1, is_list/1, ...

spawn/1, send/2, node/0, self/0, ...

2. Documentations

2.1. Documentation And STDLIB

• array, lists, dict, string, queue

• erlang

• io

• file, filename

• random, math

http://www.erlang.org/doc/man/

3. Recursive Functions

3.1. Recursion

• Primitive recursion: sum

• Tail-recursion: sum_acc

3.2. Primitive Recursion

-module(a).

-export([sum/1]).

sum(0) -> 0;

sum(N) ->

(24)

Lecture 4

N + sum(N-1).

3.3. Tail-Recursion

-module(a).

-export([sum/1]).

sum(N) -> sum(N, 0).

sum(0, Acc) -> Acc;

sum(N, Acc) ->

sum(N-1, N+Acc).

3.4. Tail-Recurssive Fibonacci

fib(N) ->

fib(N, 1, 0).

fib(0, Acc1, Acc2) ->

Acc2;

fib(1, Acc1, Acc2) ->

Acc1;

fib(N, Acc1, Acc2) ->

fib(N-1, Acc2+Acc1, Acc1).

4. Lists

4.1. Lists

http://www.erlang.org/doc/man/

-- and ++

length/1, tl/1, hd/1

• Module lists: {max/1, sum/1, nth/2, last/1, reverse/1, member/2, delete/2, sort/1, usort/1, zip/2, split/2}

• Module proplists: [{apple, 1}, {cat, 2}, {school, 3}]

4.2. List Comprehension

[what to produce?

|| from which element?, what kind of?]

[’elements’ || generator1, ..., filter1, ...]

• generator: Pattern <- List

• filter: Boolean expressions

(25)

[math:pow(X,2)||

X <- lists:seq(1, 1000), (X rem 2) == 0]

[math:pow(X,Y)||

X <- lists:seq(1, 1000), Y <- [1,2,3,4],

(X rem 2) == 0, X > 500]

4.4. QuickSort

quicksort([]) ->

[];

quicksort(List) ->

quicksort([X || X <- List, X =< Y]) ++ [Y]

++ quicksort([X || X <- List, X > Y])

4.5. Primitive Recursion

-module(a).

-export([sum/1]).

sum([]) -> 0;

sum([Head | Tail]) ->

Head + sum(Tail).

4.6. Tail-Recursion

-module(a).

-export([sum/1]).

sum(List) -> sum(List, 0).

sum([], Acc) -> Acc;

sum([Head | Tail], Acc) ->

sum(Tail, Head+Acc).

(26)

Chapter 5. Lecture 5

1. Guards

1.1. Guard Expressions

• ‟,‟ and ‟;‟

• Bound variables

• Literal

• Comparison

• Arithmetic expression

• Boolean expression

• Type checking

• guard built in functions (subset of BIFs)

1.2. Guard Expressions

A == {2, 3}, B + 2 > 2; C > 3

(A == {2, 3}) and (B + 2 > 2) or (C > 3)

X andalso Y, X not Y

is_atom(A), is_list(B)

list_to_atom(A) == ’an atom’

2. Conditional Evaluation

2.1. Case Expression

case Expr of

Pattern1 [when Guard1] -> ExprList1;

...

PatternN [when GuardN] -> ExprListN end

• Scope of a variables

• variables bound outside of the case expression can be used

• if the variable bound in every clause it can be used outside of the case expression

• Joker pattern: _

2.2. Case Expression

(27)

[] -> Res = [];

[H] -> Res = [];

[_ | Tail] -> Res = Tail end,

lists:reverse(Res)

--- Res = case lists:reverse(List) of

[] -> [];

[H] -> [];

[_ | Tail] -> Tail end,

lists:reverse(Res)

2.3. If Expression

if

Guard1 -> ExprList1;

...

GuardN -> ExprListN end

• Scope of a variables

• variables bound outside of the if expression can be used

• if the variable bound in every clause it can be used outside of the if expression

• Joker guard: true

2.4. If Expression

if

X > Y -> {X-Y, Y};

X < Y -> {X, Y-X};

true -> {X, X}

end

3. Fun Expressions

3.1. Explicit Fun Expressions

fun(Pattern11,...,Pattern1M) [when Guard1] ->

ExprList1;

...

(PatternN1,...,PatternNM) [when GuardN] ->

ExprListN end

• Scope of a variables

• variables bound outside of the fun expression can be used

• variables bound in the patterns of the fun expression hide the variables bound outside of the fun expression

(28)

Lecture 5

• Joker pattern: _

3.2. Explicit Fun Expressions

Divisors = fun(N) ->

[ X || X <- lists:seq(1,N), (N rem X)==0]

end, Prime =

fun(N) when N == 0; N == 1 ->

false;

(2) ->

true;

(N) ->

Divisors(N) == [1,N]

end, Prime(5),

[X || X <- lists:seq(1,N), Prime(X)]

3.3. Implicit Fun Expressions

fun ModName:FunName/Arity fun FunName/Arity

3.4. Implicit Fun Expressions

divisors(N) ->

[ X || X <- lists:seq(1,N), (N rem X)==0].

prime(N) when N == 0; N == 1 ->

false;

prime(2) ->

true;

prime(N) ->

divisors(N) == [1,N].

lists:filter(fun prime/1, lists:seq(1,N))

4. Dynamic Function Calls

4.1. Dynamic constructs

apply(FunExpr, [Param1, ..., ParamN])

apply(Mod, Fun, [Param1, ..., ParamN])

Fun(Param1, ..., ParamN)

Mod:Fun(Param1, ..., ParamN)

4.2. Dynamic constructs

case read_par() of

{M, F} when is_atom(F), is_atom(M) ->

M:F();

{M, F, A} when is_list(A) ->

(29)

end

(30)

Chapter 6. Lecture 6

1. Run-time Errors

1.1. Types of Run-time Errors

function_clause

case_clause

if_clause

badmatch

badarg

undef

badarith

badfun

badarity

1.2. Types of Run-time Errors

1> lists:max([]).

** exception error: no function clause matching lists:max([]) (lists.erl, line 313)

2> X = 1.

1

3> X = 2.

** exception error: no match of right hand side value 2

1.3. Types of Run-time Errors

5> length({}).

** exception error: bad argument in function length/1 called as length({})

7> lists:maxxx([]).

** exception error: undefined function

(31)

lists:maxxx/1

8> 1 + apple.

** exception error: an error occurred when evaluating an arithmetic expression in operator +/2

called as 1 + apple

1.4. Trapping Run-time Errors

catch Expr

1> catch lists:max([]).

{’EXIT’,{function_clause,[{lists,max, [[]],

[{file,"lists.erl"}, {line,313}]}, ...]}}

2> X = 1.

1

3> catch X = 2.

{’EXIT’,{{badmatch,2},[{erl_eval,expr,3,[]}]}}

1.5. Trapping Run-time Errors

5> catch length({}).

{’EXIT’,{badarg,[{erlang,length,[{}],[]}, ...]}}

7> catch lists:maxxx([]).

{’EXIT’,{undef,[{lists,maxxx,[[]],[]}, ...]}}

8> catch 1 + apple.

{’EXIT’,{badarith,[{erlang,’+’,[1,apple],[]}, ...]}}

(32)

Lecture 6

1.6. Pattern Matching on the value

case catch M:F(1,2) of {’EXIT’, {undef, _} ->

"Funtion is not defined";

Value ->

{return_value, Value}

end

1.7. Trapping Run-time Errors

try ExprList of

Pattern1 [when Guard1] -> ExprList1;

...

PatternN [when GuardN] -> ExprListN catch

Class1:ExcPattern1 [when ExcGuard1] ->

ExcExprList1;

...

ClassK:ExcPatternK [when ExcGuardK] ->

ExcExprListK after

LastExprList end

Classes: error, throw, exit

1.8. Trapping Run-time Errors

try M:F(1,2) of

Value -> {return_value, Value}

catch

error:undef ->

"Funtion is not defined"

end

1.9. Raising Exeptions

erlang:error(new__error)

throw(new__exeption)

exit(program__exited)

2. Records

(33)

2.1. Records

• Creating new data structures

• Have to be defined before the first use

• Represented as tagged tuples

-record(name, {field1 [= default1], ...,

fieldn [= defaultn]}).

• Creating records:

RecExpr = #name{..., fieldi = Value, ...}

• Record field access:

RecExpr#name.fieldi

• Record update:

RecExpr#name{..., fieldi = NewValue, ...}

2.2. Records

-record(name, {field1 [= default1], ...,

fieldn [= defaultn]}).

• Record filed index:

#name.fieldi

• Record patterns:

RecExpr = #name{..., fieldi = Value, ...}

• Shell functions: rr/1, rd/2, rl/1, rf/1

• BIFs: record_info/2 (size, fields), is_record/2

2.3. Records

-record(date, {month, day, year = 1900}).

create() ->

#date{year=2012, day = 20, month = 12}.

select(Year, [Rec = #date{year = Year} | Tail]) ->

{month, Rec#date.month};

select(_Year, [_ | Tail] ->

select(Tail);

select(_Year, []) ->

(34)

Lecture 6

not_found.

3. Lazyness

3.1. “Lazy” list

next(Seq)->

fun()-> [Seq | next(Seq + 1)] end.

SeqFun0 = next(0).

[Seq1 | SeqFun1] = SeqFun0().

...

(35)

Chapter 7. Lecture 7

1. Macros

1.1. Macros

• Have to be defined before the first use

• Token level expansion

• Constant macro definition:

-define(Name, Replacement)

• Usage: ?Name

• Parametrised macro definition:

-define(Name(Var1, ..., VarN), Replacement)

• Usage: ?Name(Var1, ..., VarN)

1.2. Macros

• Stringifying macro arguments: ??Var

• Predefined macros:

?MODULE, ?MODULE_STRING, ?FILE, ?LINE, ?MACHINE

• Often put into headers:

-include(“something.hrl”)

1.3. Conditional Macros

-undef(Flag).

-ifdef(Flag).

-ifndef(Flag).

-else.

-endif.

c(Module, [{d, debug}]), c(Module, [{u, debug}]).

1.4. Macros

-define(atom, ok).

-define(atom(), ok).

-define(atom(P), list_to_atom(P)).

f() ->

{?atom, ?atom(), ?atom("String")}.

1.5. Crosscutting Macros

(36)

Lecture 7

-define(name, f).

-define(par, ()).

-define(arrowbody, -> ok).

?name?par?arrowbody.

1.6. Conditional Macros

-ifdef(debug).

f() -> ok.

-else.

f() -> nok.

-endif.

c(mod, {d, debug}).

2. Binaries

2.1. Bitstring and binary

<< Segment1, ...., SegmentN>>

• Segment: Data, Data:Sizerrr,Data:TypeSpecifier, Data:Size/TypeSpec

• TypeSpec:

{integer, float, binary, bytes, bitstrings, bits} -- {utf8, utf16, utf32} -- {signed, unsigned} -- {big, little, native}

• Example: <<X/integer-signed-little>> = <<Y>>

• pattern matching: <<Var1:4/bits, Remaining>>

2.2. Binary Comprehensions

<< <<X:3>> || X <- [1, 2, 3, 4, 5, 6, 7]>>

<< <<X:8>> || <<X:3>> <= <<41, 203, 23:5>> >>

[ X || <<X:3>> <= <<41, 203, 23:5>> ]

[ <<X>> || <<X:3>> <= <<41, 203, 23:5>> ]

3. I/O operations

3.1. Input and Output

• io module

• Reading lines: get_line("> ")

• Reading chracters: get_chars("> ", 2)

(37)

• Reading terms: read("ok, then »")

• Writing terms: write/1

• Printing out values:

format(FormatString, [Values])

3.2. Formatting

~c – ASCII characters

~f – float number with precision of six digits

~e – float number with precision of six digits

~w – Erlang term with the standard syntax

~p – Erlang term (‟pretty printed‟)

~B – Number (default decimal base)

~W and ~P – similar to ~w and ~p, but takes an extra argument, the maximum depth of term printing

3.3. File handling

file - open, close, read, write, list dirs

filename - handling file names (platform independent)

filelib - extension to the module file

io - operations on the contents of the file, adding formated text to the opened file

{ok, Dev} = file:open(File, [Mode]), file:close(Dev)

• Mode: read, write, append, exclusive, binary, etc.

3.4. File handling

Reading Erlang terms:

file:consult("file")

io:read(Dev, Promt)

io:read(Dev, Prompt, StartLine) Reading lines:

io:get_line(Dev, Prompt)

io:fread(FileDescr, Prompt, FormatString)

~d, ~u, ~-, ~f, ~#, ~s, ~a, ~c, ~l, whitespaces, ~~

Reading binaries:

file:read_file("file")

io:pread(Dev, Start, LenB), file:close(Dev)

(38)

Lecture 7

3.5. File handling

Writing Erlang terms:

io:format(Dev, FormatString, DataList)

~n, ~s, ~p, ~w, whitespaces ~10.2s Writing bytes to a file:

file:write(Dev, Bytes)

file:write_file(Filename, Bytes) – creates the file, if necessary

file:pwrite(Dev, [{Loc, Bytes}]), file:pwrite(Dev, Loc, Bytes)

• Loc: bof, eof, cur

(39)

Chapter 8. Lecture 8

1. Concurrency/Parallelism

1.1. Basics

Process

• Actor with separated memory space (own heap and stack)

• Do not share memory

• Own state

• Communication with message passing

1.2. Basics

Communication models

• Shared memory + lock

• Software transactional memory (STM)

• Futures and Promises

• Message passing: synchronous, asynchronous

1.3. Basics

Ping-pong

run() ->

Pid = spawn(fun ping/0), Pid ! {ping, self()}, receive

pong -> ok after

1000 -> nok end.

ping() ->

receive

{ping, From} -> From ! pong end.

2. Processes and Messages

2.1. Erlang Processes

• Creating processes:

spawn/3, spawn_link/3, spawn/1, etc.

Pid = spawn(Mod, Fun, [Arg1, ..., ArgN])Pid = spawn(fun Mod:Fun/0)

• Erlang VM processes: processes/1, i/0

• BIFs: self/0, pid/3

(40)

Lecture 8

2.2. Message Sending

• Message sending:

Pid ! Msg

Pid ! {msg, "Final message’’}

• Emptying the mailbox: flush/0

• BIFs: send/2

2.3. Examples

Pid1 = spawn(lists, seq, [1, 100000])

Pid2 = spawn(fun() ->

apply(lists, seq, [1,100000]) end)

self() ! apple.

flush().

2.4. Process links and error handling

link/1, spawn_link/3

• exit signal, if process terminates– normal or non-normal

process_flag(trap_exit, true)

{’EXIT’, Pid, Reason} message

unlink/1

exit(Reason), exit(Pid, Reason) – normal, kill, other

• supervision

2.5. Receive Expressions

receive

Pattern1 [when Guard1] -> ExprList1;

...

PatternN [when GuardN] -> ExprListN end

2.6. Timeout

receive

Pattern1 [when Guard1] -> ExprList1;

...

PatternN [when GuardN] -> ExprListN after

Milliseconds -> ExprListN end

Default timeout: infinity

(41)

2.7. Example

self() ! {msg, apple}, receive

{msg, Data} when Data = apple ->

fruit_arrived;

Other ->

{something_else, Other}

after

100 -> nothing_happened end

(42)

Chapter 9. Lecture 9

1. Process Registration

1.1. Registering Processes

• Giving names/aliases to processes

• Names are atoms

• Processes can be referred by the atoms

• Registration:

register(Alias, Pid) register(foo, pid(0,30,0))

1.2. Message Sending

• Message sending:

foo ! {msg, "Final message”}

• Release the name: unregister(Alias)

• VM commands: registered(), regs()

• BIF: whereis(Alias)

2. Disributed Erlang

2.1. Distributed Erlang Nodes

• Node names are atoms

• Unique names required

• Starting the node:

erl -name foo@host

erl -sname foo -setcookie bar

• BIF: node()

• ps ax | grep -i epmd

• Erlang Port Mapper Daemon

2.2. Distributed Erlang Nodes

• Connecting the nodes:

net_adm:ping(Node), monitor_node(Node, true)

(43)

• BIF: nodes()

• "Magic Cookie":

get_cookie(), set_cookie(node(), "bar")

• Remote shell: Ctrl-G: r, c

• Default transitive connection

2.3. Distributed Erlang Nodes

• Default transitive connection

• For non transitive connection use the flag connect_all false

• Hidden nodes: when -hidden flag used

• The hidden connections are not transitive

• BIF: nodes(hidden), nodes(connected)

2.4. Distributed Erlang Nodes

• Message passing:

{Name, Node} ! {msg, "Final message”}

Pid ! {msg, "Final message”}

• Spawning:

spawn(Node, Mod, Fun, [Arg1, ..., ArgN]

spawn(Node, FunExpr)

• Receiving messages: remains the same

2.5. Example Connection

Start the server node:

erl -name server@188.143.112.97

Start the client nodes:

erl -name client1@188.143.112.97 erl -name client2@188.143.112.97

2.6. Example Connection

Connect to the nodes:

(server@188.143.112.97)5>

net_adm:ping(’client1@188.143.112.97’).

pong

(server@188.143.112.97)6> nodes().

[’client1@188.143.112.97’]

(server@188.143.112.97)5>

(44)

Lecture 9

net_adm:ping(’client2@188.143.112.97’).

pong

(server@188.143.112.97)6> nodes().

[’client1@188.143.112.97’,’client2@188.143.112.97’]

2.7. Distributed Ping-Pong

run() ->

Pid = spawn(mynode@localhost, fun ping/0), Pid ! {ping, self()},

receive pong -> ok after

1000 -> nok end.

ping() ->

receive

{ping, From} -> From ! pong end.

2.8. Tools to Use

pman:start()

tv:start()

appmon:start()

(45)

Chapter 10. Lecture 10

1. Server Skeleton

1.1. Servers step-by-step

• Starting and initialising

• Waiting for clients‟ requests

• Serving clients

• Terminating

1.2. Starting the server

start(Args) ->

register(server,

spawn_link(?MODULE, init, [Args])).

init(Args)->

InitState = initialize_state(Args), loop(InitState).

loop(State)->

receive ...

end.

1.3. Handling requests

loop(State)->

receive ...

{handle, Msg} ->

NewState = handle_req(Msg, State), loop(NewState);

_Other ->

an_unhandled_message end.

handle_req(_Msg, _State)->

do_sth.

1.4. Stopping the server

loop(State)->

receive stop ->

terminate(State);

...

end.

stop() ->

server ! stop.

terminate(_State)->

(46)

Lecture 10

do_cleanup.

1.5. Server Skeleton

-module(server_skeleton).

-export([start/1, stop/0]).

-export([init/1, loop/1, terminate/1]).

start(Args) ->

register(server, spawn_link(?MODULE, init, [Args])).

stop() ->

server ! stop.

init(Args)->

InitState = initialize_state(Args), loop(InitState).

loop(State)->

receive stop ->

terminate(State);

{handle, Msg} ->

NewState = handle_req(Msg, State), loop(NewState);

_Other ->

an_unhandled_message end.

initialize_state(_Args) ->

do_init.

terminate(_State)->

do_cleanup.

handle_req(_Msg, _State)->

do_sth.

2. Software Upgrade

2.1. Software Upgrade

• Upgrading the code of the running application after compiling

• The old version is available only if there is “reference” to it

• Qualified function applications have to be used

code:load_file(Module)

• Code Server

2.2. Code Server

code:purge(Module)

code:soft_purge(Module)

code:get_path()

code:add_path*(Path)

3. ETS/DETS

(47)

3.1. ETS

• Erlang Term Storage

• %% Shared memory

• Key-Value storage for large quantities of data

• Constant time access

• Not a KV Database, no transactions

3.2. ETS operations

• Creating tables:

TableId = ets:new(TableName, [Options])

• Options: named_table, set, bag, ordered_set, duplicate_bag, private, protected, public,

{keypos, Key}, read/write_concurrency

• Deleting tables: ets:delete(TableId)

• Inserting new elements:

ets:insert(TableId, Key, Value)

• Finding elements by key: ets:lookup(TableId, Key)

• Deleting elements: ets:delete(TableId, Key)

3.3. ETS Advanced Search

ets:first(TableId), ets:next(TableId),

’$end_of_table’

ets:match(TableId, Pattern) – $1, $0

ets:match_object(TableId, Pattern)

ets:delete_object(TableId, Pattern)

ets:select(TableId, MatchSpec)

3.4. DETS

• Disk based ETS

• No transactions

• Similar interface to ETS

3.5. Tool to Use

tv:start()

(48)

Chapter 11. Lecture 11

1. Erlang OTP

1.1. OTP

• Open Telecom Platform

• Application & Libraries:

• Basic (ERTS, stdlib, kernel, system architecture support library)

• Database (Mnesia, ODBC)

• Interface & Communication (Java/C interface, SSH, SSL, XML parsing, Inets)

• Tool applications (Pman, TV, Debugger, Edoc, Syntax tools, Dialyzer)

• System design principles

2. OTP behaviours

2.1. OTP behaviours

• Design Patterns

• Framework with generic code (start, receive-send, terminate (crash))

• Separated generic and application specific parts

• Callback module – server – generic behaviour module

2.2. Example – client-server

Generic

• Server spawn

• Storing the ”Loop-Data“

• Sending request to the server

• Response to the client

• Receiving response from the server

• Stopping the server Specific

• Initialisation of the server

• Loop-Data

• Client requests

• Handling the requests

• Responses from the server

(49)

• Termination, cleaning up

2.3. OTP behaviours

• Generic Servers

• Generic Finite State Machine

• Generic Event Handler/Manager

• Supervisors

• Applications

2.4. Pro & con

Pro

• Less code

• Less bugs

• Well tested framework

• Built-in functionality (log, trace, statistics)

• Expandable

• Common programing style

• Component based terminology Con

• Extra effort to learn

• Affects the performance

2.5. Generic Servers

2.6. Generic Servers

• client-server

gen_server.erl contains the generic part

• call back module for the specific part

-behaviour(gen_server).

2.7. Starting a Server

gen_server:start_link(SrvName, CBModName, Args, Opts)

gen_server:start(SrvName, CBModName, Args, Opts) gen_server:start_link(CBModName, Args, Opts) gen_server:start(CBModName, Args, Opts)

• Server name: {local, Name}, {global, Name}

(50)

Lecture 11

• Calls: CBModName:init(Args), which returns: {ok, LoopData}

2.8. Passing Messages

gen_server:call(Name, Message)

gen_server:call(Name, Message, Timeout) gen_server:cast(Name, Message)

gen_server:cast(Name, Message, Timeout)

• Call: Synchronous – Reply

• Cast: Asynchronous

handle_call(Message, From, LoopData) ->

...

{reply, Reply, NewLoopData}.

handle_cast(Message, LoopData) ->

...

{noreply, NewLoopData}.

2.9. Stopping the Server

handle_call(Message, From, LoopData) ->

...

{stop, Reason, Reply, NewLoopData}.

handle_cast(Message, LoopData) ->

...

{stop, Reason, NewLoopData}.

gen_server:call/cast*

• Reason: normal | shutdown | term() | {shutdown,term()}

• Calls: CBModName:terminate(Reason, LoopData)

2.10. -behaviour(gen_server)

• Unexpected/system messages:

handle_info/2

• e.g. {’EXIT’, Pid, Reason}

• Hot code Upgrade: code_change/3

handle_info(Msg, State) ->

...

{noreply, NewState}.

code_change(OldVsn, State, Extra) ->

...

{ok, NewState}.

Hivatkozások

Outline

KAPCSOLÓDÓ DOKUMENTUMOK

Hence, our idea is to store the static objects - like images and HTML parts - in the Cache Storage by using Service Workers, and store the dynamic parts - like records from

♦ Although routing and protection are optical, the major part of cost is for electrical equipment (SDH client). ♦

Our analysis of the game gives useful insights into the client puzzle approach; we show, for instance, that under cer- tain conditions (which mainly depend on the computing cost of

Example: Relationship between TDP and core frequency in models of the Skylake line (Based on data from [19]).. 1.2 Milestones of the evolution of desktop and laptop processors

Both the imperative and the functional (due to lazy evaluation) implementations stop the evaluation if a “good” value is found.. Linear Search [10]) theorems are very similar. Both

It can be used for instance to investigate and model the path allocation strategies for multipath communication systems according to the client requests and the

The model takes the client’s favourite or the adviser’s recommended recipes into account, prevents unbalanced nutrition, respects the client’s eating habits and habits of

The PSTM server takes a request from the queue, executes it, and sends a response message to a client (i.e. The backbone of PSTM architecture is based on the