26
Session 1 Mohamed Samy February 2010 Three sessions about Erlang

Erlang session1

Embed Size (px)

DESCRIPTION

I gave two Erlang sessions for FCIS in 2010 (a third was planned but unfortunately not given). This is part 1.

Citation preview

Page 1: Erlang session1

Session 1Mohamed SamyFebruary 2010

Three sessions about Erlang

Page 2: Erlang session1

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)

Page 3: Erlang session1

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.

Page 4: Erlang session1

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.

Page 5: Erlang session1

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. فيه طرق للبرمجة غير كده أصل ؟

Page 6: Erlang session1

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

Page 7: Erlang session1

Contents

1st session: Sequential Erlang.

2nd session: Concurrency and Actors.

3rd session: A simple web application

Page 8: Erlang session1

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.

Page 9: Erlang session1

Erlang resources

Download from http://www.erlang.org/download.html

Lots and lots of documentation are included! Located in c:\Program files\erl5.7.4\doc\index.html Especially look at "Getting started with

Erlang" and "Erlang reference manual"

Nice, searchable version of the documentation at www.erldocs.com

Page 10: Erlang session1

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 files\erl5.7.4\doc\index.html

Nice, searchable version of the documentation at www.erldocs.com

Page 11: Erlang session1

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

Page 12: Erlang session1

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.

Page 13: Erlang session1

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?

Page 14: Erlang session1

Pattern matching 5=5.

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

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

"hello" = "hello".

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

$a = a.

Page 15: Erlang session1

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

Page 16: Erlang session1

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

Page 17: Erlang session1

Some simple I/Oio: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.

Page 18: Erlang session1

More simple I/Oio: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 Majid\n"

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

Page 19: Erlang session1

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!

Page 20: Erlang session1

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

Page 21: Erlang session1

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

Page 22: Erlang session1

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

Page 23: Erlang session1

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}).

Page 24: Erlang session1

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.

Page 25: Erlang session1

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

Page 26: Erlang session1

Next...

Processes! Actors! Ping pong!

− Thursday, 11 February 2010.