erlang

38
Erlang Amir Salimi Moi Van Jon Paik

Upload: knoton

Post on 11-Jan-2016

29 views

Category:

Documents


0 download

DESCRIPTION

Erlang. Amir Salimi Moi Van Jon Paik. Contents. Introduction History Design and Purpose Distribution Projects Clones Features Sample Code Compilation Tuples and Atoms Lists Concurrency Processes Message passing Telephony. Introduction. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Erlang

Erlang

Amir SalimiMoi VanJon Paik

Page 2: Erlang

Contents• Introduction• History• Design and Purpose• Distribution• Projects• Clones• Features• Sample Code• Compilation• Tuples and Atoms• Lists• Concurrency• Processes• Message passing• Telephony

Page 3: Erlang

Introduction

• The sequential subset is a Functional Language.

• A concurrent programming language and runtime system (follows the actor model).

• Multi-Paradigm (provides a framework in which programmers can work in a variety of styles, freely intermixing constructs from different paradigms).

Page 4: Erlang

Design and Purpose

• Initial Version was coded in Prolog (logic programming).

• Designed to Improve the development of telephony applications.

• The Ericsson Erlang implementation primarily runs interpreted virtual machine code, but it also includes a native code compiler.

Page 5: Erlang

History

• Joe Armstrong designed the 1st version in 1986.

• Bjarne Däcker.• Agner Krarup Erlang.• "Ericsson Language."

Page 6: Erlang

Distribution

• Ericsson released Erlang as open source – Independence from a single vendor.– Increase awareness about the language.

• Erlang, together with libraries and the real-time distributed database Mnesia, forms the Open Telecom Platform (OTP) collection of libraries.

• Nortel• T-Mobile

Page 7: Erlang

Erlang Projects• Yahoo! Delicious• ejabberd - an XMPP instant messaging server • Wings 3D - a 3D modeller • the Yaws web server • Twitterfall - a service to view trends and patterns from

Twitter• Nitrogen - an event-driven web framework with

support for Web 2.0 features • The Facebook Chat system• Apache CouchDB - a distributed document-oriented

database

Page 8: Erlang

Erlang Inspired Concurrency Facilities

• C#: Retlang• Python: Candygram • JavaScript: Er.js • Lisp: Termite Scheme, erlang-in-lisp, CL-MUPROC,

Distel • PHP: PHP/Erlang • Ruby: Erlectricity • Scala • Reia

Page 9: Erlang

Features

• Hot Swapping.• Pattern matching allows for extremely

compact and clear programs.• Interfaces to other programming languages,

such as C, C++ and Java, are provided.

Page 10: Erlang

Features

• Erlang comes with design patterns or templates for client-server design, state machines, event distribution, and thread supervision.

• Erlang provides a framework that supports distribution of programs across a pool of servers, with automatic recovery and redistribution whenever a server fails.

Page 11: Erlang

Features

• It also includes powerful components for a network systems including an HTTP server, a Simple Network Management Protocol (SNMP) agent, a Common Object Request Broker Architecture (CORBA) interface, an OAM subsystem, and a fully distributed database engine.

Page 12: Erlang

Features

• Erlang's bytecode is identical on all platforms, and a network of Erlang nodes may consist of any mix of NT, UNIX, or other supported platforms.

• Erlang programs are able to handle much more load than any other languages out there, which is perfect for telephone company switches.

Page 13: Erlang

Sample Code-module(sample).            %module name

-export([double/1]).        %exported function

 

double(X) → 2 * X.          %function code

• The 1st line is the module name, which is the same

as the file name (ex. modulename.erl).• The 2nd line is exporting the function of the module.• The 3rd line is the function code itself. • X is a variable.

Page 14: Erlang

Compilation

• Type in “c(module_name).“ in the shell.• To compile top code “c(sample).”• Should get “{ok,sample}”, if not then there's

error in your code.• To run program type in

“module_name:function_name(arguments).”• To run top program “sample:double(10).” This

will return 20.

Page 15: Erlang

Factorial-module(fact).               %module name-export([fac/1, mult/2]).     %2 exported functions fac(1) ->   1;                %return 1 if fac(1)fac(N) ->   N * fac(N – 1).   %recursive calls mult(X, Y) ->   X * Y.        %return X * Y

• Has 2 functions in it: fac and mult • fac(1) acts like an if statement in C and Java• ; means there is more to that function• mult/2 takes in 2 arguments, therefore X & Y.

Page 16: Erlang

Fibonacci-module(fib).-export([fib/1]). fib(0) -> 0;fib(1) -> 1;fib(N) -> fib(N-1) + fib(N-2).

• Return the fibonacci number• fib:fib(5) returns 5• fib:fib(6) returns 8• fib:fib(10) returns 55

Page 17: Erlang

Tuples and Atoms-module(tup).-export([convert_length/1]). convert_length({centimeter, X}) ->   {inch, X / 2.54};convert_length({inch, Y}) ->    {centimeter, Y * 2.54}.

• Atoms are centimeter and inch

– Simply just names– Does not contains value

• Tuples are {centimeter, X} and {inch, Y}– Always enclosed in { }– Consider as one variable

Page 18: Erlang

Why Tuples?-module(con).-export([convert/2]). convert(M, inch) ->    M / 2.54;convert(N, centimeter) ->    N * 2.54. • Running command con:convert(3, inch). will return 1.181102...

– Is 3 in inches or centimeters?– confusing

• Running command tup:convert_length({inch, 5}). will return {centimeter,12.7}– 5 inches convert into 12.7 centimeters

• It is a way to group variables, so it's easier to understand.

Page 19: Erlang

Lists

• Lists in Erlang are surrounded by "[" and "]".• Example:

• [ 1, 2, 3, 4, 5 ] or [ { 1, blue }, { 2, red }, { 3, yellow } ]

• The | is used to separate the list.• Example: [ First | TheRest ] = [ 1, 2, 3, 4 ]

– First = 1– TheRest = [ 2, 3, 4 ]

Page 20: Erlang

List Code-module(list).

-export([list_length/1]).

 

list_length([]) ->    0;   

list_length([First | Rest]) -> 1 + list_length(Rest).

• list:list_length([1,2,3,4]). will return 4 • List is comparable to array and link list in other

programming language.

Page 21: Erlang

Concurrency in Erlang

• Erlang’s main strength is its support for concurrency.

• All concurrency is explicit in Erlang.• Processes communicate using message

passing instead of shared variables.

Page 22: Erlang

Posix/Windows Processes

• Posix and Windows thread implementations are designed to support statically typed languages that have no garbage collection information, so they cannot move or resize stacks (they don’t know where the pointers are and can’t fix them.)

• The programmer has to say how big the stacks will be, and have to overestimate with a large safety factor or else the program will not run.

Page 23: Erlang

Erlang Processes

• Erlang processes are neither operating system processes nor operating system threads

• Erlang processes do keep around enough garbage collection information to fix the necessary pointers whenever a stack has to be moved or resized

• The programmer never has to make a guess about how big to make a stack

• Stacks can start very small in size

Page 24: Erlang

Process Switching

• Posix and Windows thread implementations need the help of the OS for several operations, such as context switches.

• Context switches are very bad for caches; a context switch can mess up a cache to the point where it takes thousands of instructions to recover

• Erlang processes are green threads – no kernel memory is needed for an Erlang process, and all process switching is done by the application.

Page 25: Erlang

Erlang vs. Java

• Java is an imperative programming language; computation is done by accessing mutable shared objects

• Erlang requires no locking for routine calculations, ie, no mutex or any semaphores

Page 26: Erlang

Processes

Pid2 = spawn(Mod, Func, Args)

Page 27: Erlang

Processes

Pid2 = spawn(Mod, Func, Args)

Pid2 is process identifier of the new process - this is known only to process Pid1.

Page 28: Erlang

Message Passing

• Processes are isolated, no process can access another process's data in any way, so there is no need for locking (semaphores, mutexes) for routine calculations. (Saves time)

• The only permissible way to exchange information is message passing.

• This simplifies writing thread “safe” code.

Page 29: Erlang

Message Passing

self() - returns the Process Identity (Pid) of the process executing this function.From and Msg become bound when the message is received. Messages can carry data.

Page 30: Erlang

Message Passing

Messages can carry data and be selectively unpacked. The variables A and D become bound when receiving the message.

If A is bound before receiving a message then only data from this process is accepted.

Page 31: Erlang

Selective Message Reception

The message foo is received, then the message bar – irrespective of the order in which they were sent.

Page 32: Erlang

Selection of Any Message

The first message to arrive at the process C will be processed – the variable Msg in the process C will be bound to one of the atoms foo or bar depending on which arrives first.

Page 33: Erlang

Telephony

ringing_a(A, B) -> receive

{A, on_hook} -> A ! {stop_tone, ring}, B ! terminate, idle(A);

{B, answered} -> A ! {stop_tone, ring}, switch ! {connect, A, B}, conversation_a(A, B)

end.

Page 34: Erlang

Client Server Model

Page 35: Erlang

Timeouts

If the message foo is received from A within the time Time perform Actions1 otherwise perform Actions2.

Page 36: Erlang

Uses of Timeoutssleep(T)- process suspends for T ms.

sleep(T) -> receive after

T -> true

end.

suspend() - process suspends indefinitely.

suspend() -> receive after

infinity -> true

end.

Page 37: Erlang

Conclusion

• Erlang is a concurrent functional language designed to improve the development of telephony applications.

• It runs fast and the code is compact and easy to read.

• It is becoming more popular due to the arising need for concurrent programming.

Page 38: Erlang

Erlang

Amir SalimiMoi VanJon Paik