Crash Course

40
Erlang Crash Course E r i c sso n So f tware Technology AB , All rights Re se r v e d 1 © Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 1 Erlang Crash Course Erlang Crash Course Erlang Systems http://www.ericsson.se/erlang Ericsson Software Technology AB This is a quick crash course on Erlang. You will get the general picture of how to use the language. However this is not a detailed coverage of the language and its use.

Transcript of Crash Course

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 1

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 1

Erlang Crash CourseErlang Crash Course

Erlang Systems

http://www.ericsson.se/erlang

Ericsson Software Technology AB

This is a quick crash course on Erlang. You will get the general picture ofhow to use the language. However this is not a detailed coverage of thelanguage and its use.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 2

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 2

✷ Introduction

✷ Sequential Erlang

✷ Concurrent Erlang

✷ Fault Tolerance

✷ Interoperability

✷ Distribution

✷ Examples & Exercises

ContentsContents

During this crash course we cover these topics. We will leave out somedetails, but most of it is here.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 3

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 3

IntroductionIntroduction

✷ History of Erlang

✷ Overview of Erlang

✷ How To Run

This session contains some initial background information.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 4

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 4

History of ErlangHistory of Erlang

1987 First experiments1988-89 User prototyping telecom applications

1990 Presented at ISS’901991 A new fast implementation

1992 Product projects started1993 Distribution is added

1994 Products launched

1997 Erlang general availabilit y

1995- Several projects started

Erlang came out of the Computer Science Lab at Ellemtel Utvecklings AB,headed by Bjarne Däcker, as the result of a project trying to findprogramming languages suitable for telecom applications.

The lab tried various languages available at that time, and found the need fora language that could handle massive concurrency and having good supportfor fault tolerance. Since no language could meet these constraints, a decisionwere taken to construct a new language borrowing ideas that were good.

After some initial work, a prototype project within Ericsson were located, andsome real user response could be obtained.

The outcome of these experiments were very promising and developmentcontinued.

Today we are in a situation were we have a lot of experience from telecomapplications, and Erlang certainly fil ls its place here.

1993 Erlang Systems were founded in order to handle consultancy services,training, support and marketing.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 5

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 5

Overview of ErlangOverview of Erlang

HW/OS

ERTS (Erlang RunTime System)

Support Libraries

Applications

The Erlang system is based on a runtime environment which is the basis forprogram execution. This makes Erlang programs easily portable since onlythe ERTS needs to be ported. ERTS is currently ported to a number ofplatforms.

Applications are typically written using direct calls into the runtime system orusing support libraries for special functionality, e.g. I/O.

Together with the runtime system and the support libraries the distributioncontains applications, such as compilers and debuggers.

To really levitate your application building you should spend some timegoing through the documentation covering the support libraries.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 6

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 6

How To RunHow To Run

Erlang development consists of editing/compiling/ running.

✷ Edit in your favourite editor.

✷ Start an Erlang shell ( erl )

✷ Compile (c(filename).)

✷ Run your example.

Erlang source code files should have the suff ix . e r l

Besides running your code from the shell you can try out various stuff, pleasedo that while going through the crash course.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 7

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 7

Sequential ErlangSequential Erlang

✷ Data types

✷ Pattern matching

✷ Functions

✷ Control structures

✷ BIF’s

✷ Special i tems

Erlang is a very small language but contains a number of powerfulmechanisms that nevertheless gives you what you want in terms ofexpressability. In this session we will cover the sequential part of Erlang.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 8

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 8

Data types - TermsData types - Terms

The usual ones ....

✷ Integers (e.g. -4711, 17, 42, 4711)

✷ Characters (are really special integers)(e.g. $A meaning 65)

✷ Floats (e.g. -42.0, 17,4711)

✷ Bignums (e.g. 471117471142424242424241...)

These are the usual data types.

Bignums are a special form of integers allowing (almost) indefinite integers.

Integers overflow into bignums.

The notion t e r m is used as a generic name for any data in Erlang.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 9

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 9

More Simple TypesMore Simple Types

✷ Atoms (e.g. t h i si sa n a t o m ,o r _ l i k e _ t h i s)

✷ Variables (e.g. No t a n a t o m ,Or L i k e T h i s)

✷ References

✷ Pids

✷ Ports

An atom could be compared to a constant. The value of the atom is the atomitself. An atom name starts with a lower case letter.

A var iable is a variable in the mathematical sense. You cannot change thevalue of a variable once it has been bound. A variable name starts with anupper case letter.

A reference is nothing but a unique value within the system. This value is notunique among several invocations of the runtime system.

The other types process identifier (Pids) and por ts we wil l get back to lateron.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 1 0

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 10

Structured TypesStructured Types

✷ Tuples (e.g. {} , { 1,a} , { { a,b} , 1} )

✷ Lists (e.g. [] , [1,2], [1,a,{ 1} , [1,2]])

✷ Strings are special l ists of ASCII values,(e.g. “This is a string” )

✷ Binaries

A tuple is a container of a fixed number of terms. This is the equivalent of avector (taking all sorts of scalars) in other languages.

A list is a container of a variable number of terms. This is the equivalent of alinked list.

A binary is really a blob of memory. It is used as an platform independentstorage format. Terms may be transformed into binaries, and vice versa.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 1 1

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 11

Constructing DataConstructing Data

✷ Data is declared and constructed by simplytyping terms down.

✷ For lists there is a special construction, toprepend an element to a list L :[ e l e m e n t | L ]this should be read as ‘ the list starting withe l e m e n t and followed by the list L ’ .

Erlang is a dynamically typed language. You cannot declare a type, thesystem keeps track of this for you.

The list construction may also be used to extract element from a list, supposewe have the expression:

[ A | L ] = [ 1 , 2 , 3 ]

then A will be bound to 1, whereas L will be bound to [ 2 , 3 ]

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 1 2

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 12

Pattern MatchingPattern Matching

✷ AssignmentA = 2

✷ TestA = 2,..... A = B

✷ Extracting information{ FirstElem, SecondElem} = Tuple

Pattern matching is of fundamental importance in Erlang. Everything is basedon it.

A pattern is as the name suggests a pattern of Erlang terms. Matching is basedon the following:

‘What values should I assign to variables in the left hand side of a patternmatching to make the ‘=‘ statement a true statement’ .

In our first example, assuming that A has no value, we see that in order forthe statement ‘A = 2’ to be true A must be 2.

In the second example, when we use matching for testing purposes we haveassigned A the value 2, and then later we use it to check whether A = B istrue, i.e. we check whether 2 = B is true. This is so if B holds the value 2.

In the last example pattern matching is used to extract elements from a tuple.Thus if T u p l e contained the value { f i r st , se c o n d } thenF i r st E l e m would be bound to f i r st , and S e c o n d E l e mto se c o n d .

If a matching fails, it causes a runtime failure.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 1 3

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 13

FunctionsFunctions

double(X) -> 2 * X.

isemptylist([]) ->true;

isemptylist(_Other) ->false.

Functions consist of two parts, the h e a d and the b o d y , these areseparated by the ‘->‘ . The head consists of the name of the function(d o u b l e resp. i se m p t y l i st above) plus a argument sequencewithin parenthesis.

Arguments are given a value at a call to a function. The last expressionevaluated in the body of a function is the return value of the function.

A function may consist of several clauses (e.g. i se m p t y l i st above).Clauses are separated by ‘ ;’ . A function definition is ended using ‘ .’ .

In this example we have defined two functions, d o u b l e / 1 taking anumber as argument and returns two times this number.

The function i se m p t y l i st / 1 uses pattern matching to checkwhether the argument is the empty list ([]) or not. The returned values areordinary atoms, not Boolean values.

Erlang functions are always call by value. No variables may be imported to orexported out of a function.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 1 4

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 14

Functions - ModulesFunctions - Modules

A module:

-module(mymod).-export([double/1]).

double(X) ->2*X.

quadruple(X) ->double(double(X)).

Erlang functions must be placed in modules. There are both source modulesand binary modules. The binary ones are compiled versions of the sourcemodule.

A source module has the suff ix ‘ .erl’ , e.g. mymod.erl above. The compiledversion has the suffix ‘ .jam’ .

The structure of a source module is as above, first we need to declare thename of the module as well as the functions that we export. Naming offunctions are based on the schema n a m e / a r i t y , which uniquelydesignates a function.

Exported functions are accessible from other modules. All functions within amodule is callable from the module itself without exporting them.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 1 5

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 15

GuardsGuards

%%% Checks if the argument is an atom or an integer

atomorint(Atom) when atom(Atom) -> true;atomorint(Int) when integer(Int) -> true;atomorint(_Other) -> false.

The reserved word wh e n may be used in the head of a clause to addspecial constraints, so called guards to a clause. Guards are evaluated duringthe selection of a clause. Due to this, the selection of guards are limited.

Multiple guards may be given as a comma separated sequence after the when.The comma is interpreted as an and.

Examples of guards are:

== (equali ty)

=/= (non equality)

lists(L) (checks if L is a list)

tuple(Tup)

binary(Bin)

pid(Pid)

port(Port)

length(List)

relational operators

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 1 6

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 16

Control StructuresControl Structures

%%% The case statementfoo() -> case bar(X) of

{ case1, Arg} -> handle_it(Arg);

{ case2, Value} -> handle2(Value);Anything -> true

end,....

%%% If statementzot(X) -> if

X == 2 -> xeq2();X == 3 -> xeq3();true -> true

end,....

The case statement allows the user to base continued execution on anevaluated value. The case statement contains one or several clauses. The first(top-down) matching clause is chosen for execution.

At least one clause must match.

The if statement may only use guard operators in the tests.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 1 7

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 17

BIF’sBIF’s

✷ OS related functions, date(), time()

✷ Process related functions

✷ Math

✷ ... and more

When writing Erlang applications the code is drawn from essentially threesources.

1) Your own code

2) Library functions supplied with Erlang systems, e.g. socket

3) Built In Functions (BIF’s).

The BIF’s are functions that are impossible to do in Erlang or otherwisewould be very inefficient.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 1 8

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 18

Special ItemsSpecial Items

%%% To call any function in runtime

callany(Module, Function, Args) -> apply(Module, Function, Args).

The BIF apply/3 allows runtime creation of a call. The function returnswhatever the called function returns or failure.

This is a very powerful instrument.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 1 9

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 19

Concurrent ErlangConcurrent Erlang

✷ Creating processes

✷ Process communication

✷ Timeouts

✷ Registration

During this session we wil l talk about how to create process, how theycommunicate with each other.

You must keep in mind that Erlang processes are extremely light-weight. Donot be afraid of using a lot of processes.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 2 0

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 20

Creating ProcessesCreating Processes

Before After

PidB = spawn(mymod, myfunc, [arg1])

A

B

A

To create a new process we use the BIF sp a wn / 3 . The BIF takes threearguments, the name of a module and function that the new process will startto execute after creation, and an parameter specifying the arguments to thisfunction, this must be a list where the elements corresponds to the requiredarguments of the called function.

The BIF returns the process identifier (Pid) of the newly created process. Thenew process knows nothing about the creator (c.f. fork).

Functions used in the spawn call must be exported.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 2 1

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 21

Process CommunicationProcess Communication

A B

B ! { mymsg, [1,2,3]}....

receive {mymsg, List} ->

handle(List); AnyMsg ->

trueend,

To send a message to another process we need to know its pid. Any term maybe sent as a message. In the example above process A sends a tuple to processB. The message is ‘ tagged’ with the atom m y m sg , to allow selection atthe receiver end.

Messages are asynchronous, thus A continues to execute after sending themessage. A will not be notified if B is non-existent (we get back to this lateron).

To be able to receive a message a process must execute a receive statement.A receive statement may contain several clauses, and the selection of a clauseis based on pattern matching.

Each process is said to have a mailbox, where messages are stored in a queue.As soon as a process executes a receive statement, the first message in thebox is matched top-down against the clauses, if any of them matches, themessage is removed from the mailbox and execution proceeds. If the messagedoesn’ t match any clause, the message is left in the mailbox and the nextmessage is tried in a similar fashion. If no message matches, then the processis put to sleep until such a message appears.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 2 2

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 22

Time-outsTime-outs

receive SomeMsg ->

handle_it(SomeMsg) after 1000 ->

handle_timeout()end,...

%%% To specify a maximum waiting time

To avoid locking processes, a time out may be specified in the receivestatement. The time is specified in mill iseconds. If no matching message isreceived within the given time frame, the time-out clause is chosen.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 2 3

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 23

Example UsageExample Usage

%%% Sleep Time ms

sleep(Time) -> receive

after Time -> true

end.

%%% Flush messages

flush() -> receive

Any -> flush()after 0 -> true

end,....

Using a 0 (zero) as time-out time means simply that if no message isapplicable we should time-out, or as in the example above leave the receivestatement.

The second example shows how the message queue may be flushed.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 2 4

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 24

RegistrationRegistration

A

register(myname, self()), B

myname ! Msg

A process may be registered under a name, an alias. To do this the BIFr e g i st e r / 2 must be used. The function takes two arguments, thename of the process and the process id. Above we have used the BIFse l f / 0 to obtain our own process id.

Other processes may now use the name when communicating with the namedprocess. In this way we do not have to circulate the pid around the system.

The name of the process must be unique within the Erlang system. If theprocess dies the name is no longer valid.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 2 5

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 25

Fault ToleranceFault Tolerance

✷ Exits

✷ Exit signals

✷ Trapping exits

Fault tolerance is one of the fundamental issues in Erlang. The basicmechanism for this is process links and exit signalling.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 2 6

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 26

✷ Exiting a spawn function

✷ Exiting

ExitsExits

start() -> do_things(), true.

exit(Reason)

There are three ways for a process to terminate:

A process could terminate due to falling over the function edge (of a spawnfunction), i.e. have nothing more to execute.

A process may also encounter an error, such as division by zero. This alsoterminates the process.

A process may also choose to terminate using the BIF e x i t / 1 .

There is always a reason associated with exiting. In the first case the reason iscalled n o r m a l . In the second case, the nature of the failure is the reason,e.g. function clause missing. Finally in the last case the reason is supplied inthe call to e x i t / 1 .

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 2 7

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 27

Exit SignalsExit Signals

link(A)A B

link

A B

A

X = 1/0

By using the BIF l i n k / 1 bi-directional links may be set up betweenprocesses. A process may link to multiple processes. When a process dieswith reason different from n o r m a l , an exit signal is sent along thelinks, killing the other processes in the linked set. Exit signal propagatesthrough linked sets.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 2 8

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 28

Trapping ExitsTrapping Exits

A

process_flag(trap_exit, true)

B

A B

receive { ‘EXIT’ , B, Reason} ->

.....

A process may choose to trap exits. This means that exit signals from thelinked set will be transformed into exit messages that may be received by theexit trapping process. Exit signals will not propagate through the exit trappingprocess.

The purpose of this arrangement is to let the process A know about the failureof B and thus take action.

An exit trapping process may choose to exit as well, but this must be doneexplicitly.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 2 9

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 29

InteroperabilityInteroperability

Erlang program

Other programconnectedprocess

port

pipe

Erlang interoperates with other programs through por ts. A port is a bi-directional communication path, typically using pipes.

A port is opened by a process, this process is known as the connectedprocess. This process is allowed to send messages to the port and it is alsothe designated receiver of messages from the port. These messages originatefrom the other program connected to the port.

In an application the connected process typically acts as a concentrator anddistributor of the information flow between processes and the other program.

The other program is supposed to read and write to stdin/stdout (typically).

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 3 0

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 30

Using PortsUsing Ports

Port ! { self(), { command, [1,2,3,4,5]}}

A

Port = open_port({ spawn, myprog} , [{ packet, 2} ])

myprog[0,5,1,2,3,4,5]

len = read(0,buff,2);len = buff[0]<<8 | buff [1];read(0, buff, len);

A process needs to open a port before using it. In this case we specify that theport should be connected to a spawned OS program called m y p r o g . Wealso say that we use packages with a 2 byte length header prepended to themessage. The message sent is a list of 8 bit integers while the receivedmessage is a sequence of bytes (C-side).

Note that the receiving program should check the read length.

Handling of lengths etc., is not needed in the Erlang environment. At theErlang side only lists are seen.

As an option (which is more common), binaries may be used at the Erlangside. Other package sizes are supported as well.

There are C-libraries helping out with encoding/decoding Erlang terms.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 3 1

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 31

DistributionDistribution

[email protected] [email protected] [email protected]

> erl -name node1 > erl -name node2 > erl -name node1

B

C

B ! Msg

link(C)

%% Monitoringmonitor_node(Node, true),receive { nodedown, Node} ->

downend

The Erlang distribution is based on nodes. A node is an Erlang system startedin distributed mode and given a name, e.g. erl -name thename.

A node name consists of a given name and the host name. Thus above thegiven names are n o d e 1 , n o d e 2 and n o d e 1 (again). Theuniqueness of nodenames are given by the network host names.

Message sending and process linkage is transparent to the application.Processes do not have to reside within the same node.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 3 2

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 32

Distribution (more)Distribution (more)

✷ To spawn:– spawn(Node, Mod, Func, Args)

✷ Using registered names:– {thename, Node} ! Msg

When using registered names on other nodes, no notification of missing nameis made.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 3 3

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 33

Examples/ExercisesExamples/Exercises

✷ Simple recursion

✷ Simple process communication

✷ Simple RPC

In this session we wil l give you three simple examples of code.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 3 4

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 34

Simple RecursionSimple Recursion

%% Finds out if Item is in the List

member(Item, [I tem | _Rest]) -> true;member(Item, [_NotItem | Rest]) -> member(Item, Rest);member(_Item, []) -> false.

In the first clause we rely on pattern matching between the searched item andthe head of the list.

If this is not the case (clause 2) we try if there are at least one element in thelist, and if so we simply make a recursive call to try the remainder of the list.Finally in the last clause we have reached the empty list without finding thewanted item, and thus we return false.

Note that we have implicitly tested for a list as the second elementeverywhere. If this function is called with something else as second argumentthe call fails.

NB! Erlang employs Last Call Optimization (LCO) which is a technique thatreuses stack space, thus you do no have to worry about using too much stackhere.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 3 5

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 35

Simple Process Communication..Simple Process Communication..

%%% Sends a message back and forth-module(echo).-export([second/1]).

start() -> Pid = spawn(echo, second, [] ), Pid ! { hello, self()} , receive

_What -> true

end.

In this example a process creates an echo process (see next slide), then itsends a message to the echo process and then wait for the reply. After this theprocess terminates.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 3 6

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 36

..Simple Process Communication..Simple Process Communication

%% And the second processsecond() -> receive

{Msg, Pid} when pid(Pid) -> Pid ! Msg;Else -> true

end, second().

This is the code for the echo process. The process sits in a loop waiting for amessage to appear. The process reacts to messages being tuples containing amessage and a process id. The message is returned to the pid.

All other messages are discarded.

Note that this process never terminates.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 3 7

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 37

Simple RPC (server)Simple RPC (server)

%%% Assume the server is registered under the name r e x

loop() -> receive

{From, { apply, M, F, A} } -> From ! { rex, node(), apply(M, F, A)} loop();_Other -> loop()

end.

This is the essential loop needed for an RPC server.

The server receives requests from clients, uses apply to evaluate the requestsand then returns the answer to the originator.

This is a simplified solution where no error handling is done.

The BIF n o d e / 0 returns the node name.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 3 8

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 38

Simple RPC (client)Simple RPC (client)

%% This is all the client needs to do

call (Node, M, F, A) -> { rex, Node} ! { self(), { apply, M, F, A} } , receive

{ rex, Node, What} -> What

end.

This is the code needed for basic client RPC calls.

The client sends a message to a registered process at the given node and thenwaits for the reply.

This solution might be extended to handle e.g. malfunctioning servers.

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 3 9

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 39

ExercisesExercises

✷ Write a function append(List1, List2) thatreturns the concatenation of the lists.

✷ Write a program having two processes sendinga message back and forth M times, and thenterminates.

✷ Modify the program to run on two nodes.

It is up to you to solve these....

Erlang Crash Course

E r i c sso n S o f t wa r e T e c h n o l o g y AB ,Al l r i g h t s R e se r v e d 4 0

© Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 40

Sources of InformationSources of Information

✷ http://www.ericsson.se/erlang

✷ ‘Concurrent Programming in ERLANG’ ;Armstrong, Virding, Wikström, Williams;Prentice Hall, ISBN 0-13-508301-X

✷ Courses @ Erlang Systems

The book covers the general ideas as well as some examples. The web sitegives you additional information as well as more up-to-date informationabout releases etc.

In the distribution you wil l find on-line manuals that gives you the details notfound in the book.

Erlang Systems is offering an extensive set of courses covering Erlang. Forfurther information see the web site.