A apresentação está carregando. Por favor, espere

A apresentação está carregando. Por favor, espere

Erlang Programming Language

Apresentações semelhantes


Apresentação em tema: "Erlang Programming Language"— Transcrição da apresentação:

1 Erlang Programming Language
Aluísio Rodrigo (arfs) Diego Lima (dclal)

2 Roteiro Introdução Histórico Características Utilização Especificação
Implementação e Ambientes de Desenvolvimento Sintaxe Vantagens e Desvantagens Tendências

3 Introdução “Programming Erlang, Software for a Concurrent World”
Joe Armstrong, 2007

4 Introdução Linguagem de programação concorrente Open Source
Sistemas de telecomunicações Sistemas de controle Aplicações distribuídas Soft Real-Time Applications Open Source Útil para Servidores de aplicação da Internet

5 Roteiro Introdução Histórico Características Utilização Especificação
Implementação e Ambientes de Desenvolvimento Sintaxe Vantagens e Desvantagens Tendências

6 Histórico Motivação: Nenhuma linguagem para sistemas de telecomunicações 1984 – Formado Laboratório de Computação da Ericsson 1987 – criação do protótipo da linguagem Erlang Homenagem ao matemático A.K. Erlang Ericsson Language Programação de sistemas de telecomunicações 1991 – Primeira Implementação rápida 1993 – Distributed Erlang Suporte à aplicações concorrentes e distribuídas 1998 – Open Source History of Erlang - Experiments with programming of telecom using > 20 different languages. Conclusion: The language must be a very high level symbolic language in order to achive productivity gains ! (Leaves us with: Lisp , Prolog , Parlog ...) Experiments with Lisp,Prolog, Parlog etc. Conclusion: The language must contain primitives for concurrency and error recovery, and the execution model must not have back-tracking. (Rules out Lisp and Prolog.) It must also have a granularity of concurrency such that one asyncronous telephony process is represented by one process in the language. (Rules out Parlog.) We must therefore develop our own language with the desirable features of Lisp, Prolog and Parlog, but with concurrency and error recovery built into the language. 1987 The first experiments with Erlang. 1988 ACS/Dunder Phase 1. Prototype construction of PABX functionality by external users Erlang escapes from the lab! 1989 ACS/Dunder Phase 2. Reconstruction of 1/10 of the complete MD-110 system. Results: >> 10 times greater gains in efficency at construction compared with construction in PLEX!Further experiments with a fast implementation of Erlang. 1990 Erlang is presented at ISS'90, which results in several new users, e.g Bellcore. 1991 Fast implementation of Erlang is released to users. Erlang is represented at Telecom'91 . More functionality such as ASN1 - Compiler , graphical interface etc. 1992 A lot of new users, e.g several RACE projects. Erlang is ported to VxWorks, PC, Macintosh etc. Three applications using Erlang are presented at ISS'92. The two first product projects using Erlang are started. 1993 Distribution is added to Erlang, which makes it possible to run a homgeneous Erlang system on a heterogeneous hardware. Decision to sell implementations Erlang externally. Separate organization in Ericsson started to maintain and support Erlang implementations and Erlang Tools.

7 Roteiro Introdução Histórico Características Utilização Especificação
Implementação e Ambientes de Desenvolvimento Sintaxe Vantagens e Desvantagens Tendências

8 Características Linguagem Funcional Concorrência Funções matemáticas
Prova de propriedades Concorrência Baseada em processos Concorrência é explícita O usuário pode controlar quais segmentos são computados seqüencialmente e quais são feitos em paralelo Processos só trocam informações através de mensagens Programs are written entirely in terms of functions { function selection is made by pattern matching which leads to highly succinct programs. Erlang has a process-based model of concurrency. Concurrency is explicit and the user can precisely control which computations are performed sequentially and which are performed in parallel. Message passing between processes is asynchronous, that is, the sending process continues as soon as a message has been sent. The only method by which Erlang processes can exchange data is message passing. This results in applications which can easily be distributed { an application written for a uniprocessor can easily be changed to run on a multiprocessor or network of uniprocessors. Erlang has a process-based model of concurrency with asynchronous message passing. The concurrency mechanisms in Erlang are lightweight, i.e. processes require little memory, and creating and deleting processes and message passing require little computational efort.

9 Características Tempo Real Programação Distribuída
Projetada para aplicações leves em tempo real. Respostas na ordem de milissegundos. Programação Distribuída Possui mecanismos que facilitam a escrita de aplicações que possam rodar tanto em um único computador como em uma rede de computadores Erlang is suitable for most soft real-time applications where response times are in the order of milliseconds. The language has built-in mechanisms for distributed programming which makes it easy to write applications which can run either on a single computer, or on a network of computers. Variables in Erlang have the property of single assignment3 { once a value has been assigned to a variable this value can never be changed. This property has important consequences when debugging or transforming a program. The Erlang system has an inbuilt notion of time { the programmer can specify how long a process should wait for a message before taking some action. This allows the programming of real-time applications.

10 Características Robustez Gerenciamento de Memória Integração
Tolerância a falhas Operação contínua Primitivas de carregamento de código Gerenciamento de Memória Garbage Collector Processos não compartilham memória Integração Pode ser integrado facilmente com programas em outras linguagens Many of the Erlang primitives provide solutions to problems which are commonly encountered when programming large concurrent real-time systems. The module system allows the structuring of very large programs into conceptually manageable units. Error detection mechanisms allow the construction of faulttolerant software. Code loading primitives allow code in a running system to be changed without stopping the system. Erlang is a symbolic programming language with a real-time garbage collector. Memory is allocated automatically when required, and deallocated when no longer used. Typical programming errors associated with memory management cannot occur Erlang has no shared memory. All interaction between processes is by asynchronous message passing. Distributed systems can easily be built in Erlang. Applications written for a single processor can, without di- culty, be ported to run on networks of processors. Integration. Erlang can easily call or make use of programs written in other programming languages. These can be interfaced to the system in such a way that they appear to the programmer as if they were written in Erlang.

11 Roteiro Introdução Histórico Características Utilização Especificação
Implementação e Ambientes de Desenvolvimento Sintaxe Vantagens e Desvantagens Tendências

12 Utilização Synap.se: Billing & device configuration
Blue Position: Bluetooth Location Information System Motivity: Answer Supervision Generator, Signalling Gateway Telia: CTI Platform Corelatus: Signalling gateways & cross-connects Bluetail/TeleNordia: Robust SMTP Mail Server Univ. of Coruña: VoD Cluster Ericsson: AXD 301, GPRS, (NetSim), LCS Nortel: SSL Accelerator, SSL VPN gateway + others TMobile: IN applications Vail Systems: Computer Telephony Apps Service Prov. Erlang Financial Systems: Banking & Lottery systems Mobile Arts: Presence & Messaging for GSM/UMTS Vail Systems: Sistema de Resposta de Voz Interativa Erlang Finantial System: Bancos e Sistemas lotéricos. Blue Position: Sistema de localização de dispositivos bloetooth Telia: Plataformas CTI Bluetail/TeleNordia: Robusto serviço SMTP para Univ. of Corunã: VoD Clusters

13 Roteiro Introdução Histórico Características Utilização Especificação
Implementação e Ambientes de Desenvolvimento Sintaxe Vantagens e Desvantagens Tendências

14 Especificação Open Source Erlang Getting Started Documentation
Getting Started Documentation Examples Downloads Source Binary A especificação de Erlang era de propriedade da Ericsson até 1998, quando a linguagem tornou-se Open Source. Muito da especificação pode ser encontrada no site que contém os seguintes itens: Getting Started: para iniciantes é uma iniciação rápida na linguagem, interessante para quem já conhece programação, principalmente programação com linguagens funcionais. Possui também um guia somente detalhando como utilizar o Erlang para programação concorrente; About Erlang: Comentários sobre a linguagem; Documentation: com a especificação da linguagem; Projects: Listados alguns projetos que utilizam Erlang. Também são disponibilizados textos de como desenvolver aplicações mais complexas com a linguagem. Além disso, trabalhos como artigos, tutoriais e programas exemplos estão à disposição.

15 Roteiro Introdução Histórico Características Utilização Especificação
Implementação e Ambientes de Desenvolvimento Sintaxe Vantagens e Desvantagens Tendências

16 Implementação Tipos de Implementação Open Source Erlang
Implementação mais popular Inclui a biblioteca OTP (Open Telecom Plataform) Corba, Databases, GUI Ericsson’s Comercial Erlang Essencialmente a mesma da Open Source Oferece suporte Open Source Erlang - É a implementação mais popular, baseada na versão comercial da Ericsson®. Pode ser usada sem necessidade de pagamento de royalties à Ericsson®. A biblioteca OTP (Open Telecom Platform) está incluída e também é open source. A maioria dos projetos "Erlang" são projetos "Erlang/OTP". OTP é uma extensa biblioteca para Erlang capaz de dar suporte à implementação desde servidores WWW à compilação de ASN.1. Entre suas implementações inclui: Suporte à Operações e Manutenção: SASL (Simple Authentication and Security Layer), SNMP (Simple Network Management Protocol). CORBA: suporte a todas suas funcionalidades. Database: Mnesia and Mnemosyne provêem banco de dados em tempo real distribuído que pode ser in-RAM e on-disk. Também possui um driver cliente standard ODBC (Open Database Connectivity). ASN. 1 (Abstract Syntax Notation): Compilador ASN.1 que produz código Erlang. Biblioteca Padrão: Ampla coleção de módulos que lidam desde strings, listas e manipulação de expressões regulares à geração de números aleatórios e pesquisa de calendário. Componentes Estruturais: gen_server, gen_fsm, e supervisão de árvores para implementação de subsistemas cliente/servidor, máquinas de estados e sistemas de tolerância à falhas supervisionado. GUI e Gráficos: gs e webtool para implementar interfaces gráficas. gs opera tanto com Windows quanto com Unix (X Window System). Ericsson's Commercial Erlang - Essencialmente a mesma da Open Source, com as seguintes diferenças: Possui um acordo de suporte pago. A equipe OTP testa seus produtos com mais rigor, sendo mais estável. Não possui aplicações consideradas instáveis ou experimentais. O código da linguagem é interpretado por uma Máquina Virtual (virtual machine code), mas também possui um compilador nativo (não suportado em todas as plataformas), desenvolvido pela HiPE (High Performance Project) na Universidade de Uppsala.

17 Implementação Máquinas Virtuais
New BEAN (Bogdan/Björn's Erlang Abstract Machine) Utilizada na versão comercial JAM (Joe’s Abstract Machine) A máquina virtual original de Erlang inspirada em Prolog Old BEAN Transformar de Erlang para C e depois para código nativo Foi abandonado devido a problemas com eficiência O código da linguagem é interpretado por uma Máquina Virtual (virtual machine code), mas também possui um compilador nativo (não suportado em todas as plataformas), desenvolvido pela HiPE (High Performance Project) na Universidade de Uppsala. Máquina Virtual Erlang: A maioria das implemetações usam new BEAM (Bogdan/Björn's Erlang Abstract Machine), essa é usada na versão comercial. Outras Máquinas Virtuais são de interesse histórico: JAM (Joe's Abstract Machine) - A MV original de Erlang inspirada em WAM de Prolog. old BEAM - Uma tentativa de compilar Erlang para C, e depois de C para código nativo. Foi abandonado após teste de benchmarking mostrarem que o código resultante era mais rápido em relação à MV-Erlang somente para programas pequenos. Sistemas Operacionais suportados pela Máquina Virtual: Unix e similares Solaris (including 64 bit) BSD Linux OSX TRU64 Windows NT/2000/2003/XP Windows 95, 98 VxWorks

18 Ambientes de Desenvolvimento
Erlang Shell Desenvolvido pela Ericsson ErlyBird IDE baseado no NetBeans Erlide Plug-in para o Eclipse Instalação: Erlide - Um plug-in para o IDE Eclipse 3.2; ErlyBird IDE baseado no NetBeans; Erlang Shell Ericsson Telecom AB. Todos esses ambientes são gratuitos.

19 Roteiro Introdução Histórico Características Utilização Especificação
Implementação e Ambientes de Desenvolvimento Sintaxe Vantagens e Desvantagens Tendências Erlang é basicamente uma linguagem funcional sem tipos como ML e LISP, com sintaxe inspirada em Prolog combinada com elementos encontrados em linguagens de programação de sistemas em tempo real como process construts, passagem de mensagem e um avançado tratamento de exceções. A linguagem também fornece um poderoso suporte para programação distribuída.

20 Sintaxe Números Integers Floats 10. -234. 2#110111010. (BASE#VALOR)
$A. ($CHAR) Floats 12.34E-10. B#Val is used to store numbers in base < B &gt. $Char is used for ascii values (example $A instead of 65).

21 Sintaxe Átomos O valor do átomo é sua própria declaração
O tamanho do átomo é indefinido Deve possuir aspas caso não comece com uma letra em minúsculo ou contenha caracteres especiais que não seja _ ( ) hello. phone_number. ‘Monday’. ‘phone number’. An atom is a literal, a constant with name. An atom should be enclosed in single quotes (’) if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore ( ),

22 Sintaxe Tuplas Listas {123, bcd}. {person, 'Joe', 'Armstrong'}.
[123, 456]. [{person, 'Joe', 'Armstrong'}, {person, 'Robert', 'Virding'}]. Tuples: Used to store a fixed number of items. Tuples of any size are allowed. Lists: Used to store a variable number of items. Lists are dynamically sized. "..." is short for the list of integers representing the ascii character codes of the enclosed within the quotes.

23 Sintaxe Variáveis Devem começar com a primeira letra maiúscula
Ao contrário dos átomos, só alguns caracteres são permitidos A variável só pode receber o valor apenas uma vez Abc A_long_variable_name AnObjectOrientatedVariableName Start with an Upper Case Letter. No "funny characters". Variables are used to store values of data structures. Variables can only be bound once! The value of a variable can never be changed once it has been set (bound).

24 Sintaxe Casamento de Padrão {A, B, C} = {10, foo, bar}
A = 10, B = foo, C = bar [H|T] = [1,2,3,4] H = 1, T = [2,3,4] {A,_,[B|_],{C}} = {abc,1,[2,3],{4}} A = abc, B = 2, C = 4 Note the use of "_", the anonymous (don't care) variable.

25 Sintaxe Boolean String Não existe o tipo booleano em Erlang.
São utilizados os átomos true e false. String São representações de listas de inteiros “hello” = [$h,$e,$l,$l,$o] = [104,101,108,108,111] There is no Boolean data type in Erlang. Instead the atoms true and false are used to denote Boolean values. Strings are enclosed in double quotes (“), but is not a data type in Erlang. Instead a string "hello" is shorthand for the list [$h,$e,$l,$l,$o], that is [104,101,108,108,111]. Two adjacent string literals are concatenated into one.

26 Sintaxe Seqüências Especiais
Within strings and quoted atoms, the following escape sequences are recognized:

27 Sintaxe Operadores - 3. 5 + 10.0. 3 / 2. 3 div 2.
true and (1 =< 3).

28 Sintaxe Operadores Lógicos Relacionais Aritméticos

29 Sintaxe Operadores Symbol Purpose , Statement Separator ; .
Statement Terminator -> Function or Guard declaration Erlang can be a confusing language because there are two types of statement separators. The , separator is used to separate expressions. This generally comes into use when using expressions one after the other as in normal sequential programming. The ; separator is used when different levels of statement need to be terminated such as a case or guard. The . symbol is used as a terminator for function (or expression when run from a console).

30 Sintaxe Operadores de Listas Concatenação ++ Subtração --
[1,2,3]++[4,5] = [1,2,3,4,5] Subtração -- [1,2,3,2,1,2]--[2,1,2] = [3,1,2] The list concatenation operator ++ appends its second argument to its first and returns the resulting list. The list subtraction operator -- produces a list which is a copy of the first argument, subjected to the following procedure: for each element in the second argument, the first occurrence of this element (if any) is removed. [1,2,3]++[4,5]. [1,2,3,4,5] [1,2,3,2,1,2]--[2,1,2]. [3,1,2]

31 Sintaxe Expressões Expressões curto-circuito Não são lazy-evaluation
E1 + E2 – E1 e E2 são avaliadas. Expressões curto-circuito Expression_1 orelse Expression_2 Expression_1 andalso Expression_2

32 Sintaxe Módulos Em Erlang os códigos são divididos em módulos
Cada módulo consiste de uma seqüência de atributos e de declaração de funções Os atributos de um módulo definem certas propriedades . Ex.: Aridade de uma função Erlang code is divided into modules. A module consists of a sequence of attributes and function declarations, each terminated by period (.). Modules double can be called from outside the module, times is local to the module. double/1 means the function double with one argument (Note that double/1 and double/2 are two different functions).

33 Sintaxe Módulos Atributos pré-definidos: -module(Module)
-export(Functions) -import(Module,Functions) -compile(Options) -vsn(Vsn) -module(Module). Module declaration, defining the name of the module. The name Module, an atom, should be the same as the file name minus the extension erl. Otherwise code loading [page 50] will not work as intended. This attribute should be specified first and is the only attribute which is mandatory. -export(Functions). Exported functions. Specifies which of the functions defined within the module that are visible outside the module. Functions is a list [Name1/Arity1, ..., NameN/ArityN], where each NameI is an atom and ArityI an integer. -import(Module,Functions). Imported functions. Imported functions can be called the same way as local functions, that is without any module prefix. Module, an atom, specifies which module to import functions from. Functions is a list similar as for export above. -compile(Options). Compiler options. Options, which is a single option or a list of options, will be added to the option list when compiling the module. See compile(3). -vsn(Vsn). Module version. Vsn is any literal term and can be retrieved using beam lib:version/1, see [beam lib(3)]. If this attribute is not specified, the version defaults to the MD5 checksum of the module. Behaviour Module Attribute It is possible to specify that the module is the callback module for a behaviour: -behaviour(Behaviour). The atom Behaviour gives the name of the behaviour, which can be a user defined behaviour or one of the OTP standard behaviours gen server, gen fsm, gen event or supervisor. The spelling behavior is also accepted. Read more about behaviours and callback modules in OTP Design Principles.

34 Sintaxe Funções Seqüência de cláusulas separadas por ponto e vírgula e finalizada por um ponto Cada cláusula consiste de uma cabeça e de um corpo separado por -> A cabeça consiste no nome da função com uma lista de argumentos e uma guarda opcional começando com when Functions Arg1 .. Argn are any Erlang data structures. The function and module names (func and module in the above) must be atoms. A function can have zero arguments. (e.g. date() - returns the current date). Functions are defined within Modules. Functions must be exported before they can be called from outside the module where they are defined. Clauses are scanned sequentially until a match is found. When a match is found all variables occurring in the head become bound. Variables are local to each clause, and are allocated and deallocated automatically. The body is evaluated sequentially.

35 Sintaxe Funções -module(fat). -export([fatorial/1]).
fatorial (N) when N > 0 -> N * fatorial (N - 1); fatorial(_) -> 0. fat:fatorial(6).

36 Sintaxe Funções -module(calculo). -export[area/1].
area({quadrado, Lado}) -> Lado* Lado; area({retangulo, X, Y}) -> X * Y; area({circulo, Raio}) -> % aproximadamente * Raio* Raio; area({triangulo, A, B, C}) -> S = (A + B + C)/2, math:sqrt(S*(S-A)*(S-B)*(S-C)).

37 Sintaxe Algumas Built-in Functions atom_to_list(atom)
atom_to_list(hello) = “hello” float_to_list(Float) float_to_list(7.0) = " e+000" tuple_size({a,b,c}) date(), time() processes() Built-in functions, BIFs, are implemented in C code in the runtime system and do things that are difficult or impossible to implement in Erlang. Most of the built-in functions belong to the module erlang but there are also built-in functions belonging to a few other modules, for example lists and ets. Some operations are impossible to program in Erlang itself, or are impossible to program eciently. For example, there is no way to nd out the internal structure of an atom, or the time of day, etc. { these lie outside the scope of the language. Erlang therefore has a number of built-in functions (BIFs) which perform these operations. There are a number of BIFs for type conversions. Examples:

38 Sintaxe Estruturas de Controle IF if Guard1 -> Sequence1 ;
... end

39 Sintaxe Estruturas de Controle IF -module(modulo).
-export([maior_que/2]). maior_que(X, Y) -> if X > Y -> true; true -> % átomo funcionando como um else false end.

40 Sintaxe Estruturas de Controle Case case Expr of
Pattern1 [when Guard1] -> Seq1; Pattern2 [when Guard2] -> Seq2; ... end

41 Sintaxe Estruturas de Controle Case -module(redondo).
-export([eh_redondo/1]). eh_redondo(Forma) -> case Forma of {circulo, _} -> true; {quadrado, _} -> false; _ -> false end.

42 Sintaxe Escopo das variáveis
Em Erlang, variáveis em uma cláusula existem a partir do ponto que são atribuídas até a última referência textual da variável na cláusula Variáveis dentro do IF e Case são exportadas para o contexto de fora delas. Variables in a clause exist between the point where the variable is first bound and the last textual reference to that variable in the clause. The binding instance of a variable can only occur in a pattern matching operation; this can be thought of as producing the variable. All subsequent references to the variable consume the value of the variable. All variables occurring in expressions must be bound. It is illegal for the first use of a variable to occur in an expression. Variables which are introduced within the if, case or receive primitives are implicitly exported from the bodies of the primitives.

43 Sintaxe Escopo das variáveis -module(teste). -export([f/1,g/1,h/1]).
f(X) -> case g(X) of true -> A = h(X), B = 7; false -> B = 6 end, h(A), h(B).

44 Sintaxe Processo Identifica um processo que vai executar uma função
Pid = spawn(Modulo, Funcao, [args]) Identifica um processo que vai executar uma função Pid = spawn(Node, Modulo, Funcao, [args]) Aplicação distribuída Node = Nó remoto spawn starts a parallel computation (called a process)

45 Sintaxe Send Receive Pid ! {a, 12} receive Message 1 -> ... ;
Pid ! Message

46 Sintaxe -module(echo). -export([go/0, loop/0]). go() -> Pid = spawn(echo, loop, []), Pid ! {self(), hello}, receive {Pid2, Msg} -> Print = "Mensagem:" ++ atom_to_list(Msg) ++ "~nRecebido de:" ++ pid_to_list(Pid2) ++ "~n", io:format(Print,[]) end, Pid ! stop. loop() -> {From, Msg} -> From ! {self(), Msg}, loop(); stop -> true end.

47 Sintaxe Tratamento de erros Catch e Throw -module(modulo).
-export([roda_funcao/1]). funcao(1) -> hello; funcao(2) -> throw({exception, abc}); funcao(3) -> tuple_to_list(a); funcao(_) -> exit({myExit, 222}). roda_funcao(X) -> case catch funcao(X) of {exception, Args} -> "erro1"; {'EXIT',{myExit, Code}} -> "erro2"; {'EXIT', What} -> "erro3"; Other -> Other end. Catch Returns the value of Expr unless an exception occurs during the evaluation. In that case, the exception is caught. For exceptions of class error that is run-time errors: {‘EXIT’,{Reason, Stack}} is returned. For exceptions of class exit , that is the code called exit(Term): {‘EXIT’,Term} is returned. For exceptions of class throw, that is the code called throw(Term): Term is returned.

48 Sintaxe Palavras Reservadas: after and andalso band begin bnot
bor bsl bsr bxor case catch cond div end fun if let not of or orelse query receive rem try when xor Comentários %comentário

49 Sintaxe Exercícios fibonacci(X): Recebe um número inteiro positivo e retorna o n-ésimo elemento da seqüência de Fibonacci. elemento(X,Y): Recebe um número inteiro positivo e uma lista para retornar o n-ésimo elemento da lista. dobra1(X): Defina as funções dobra1(X) e dobra2() na qual a função dobra1 recebe o valor X e envia uma mensagem para o processo na qual a funcao dobra2 esta rodando. A funcao dobra2 duplica o valor passado na mensagem e retorna o valor para o processo que esta rodando dobra1

50 Roteiro Introdução Histórico Características Utilização Especificação
Implementação e Ambientes de Desenvolvimento Sintaxe Vantagens e Desvantagens Tendências

51 Vantagens Suporte à implementação de sistemas em Rede e telecomunicações Eficiência e confiabilidade Programação Concorrente Suporte à programação de sistemas distribuídos Atualizado sem necessidade de interromper sistema Pode ser integrado com Java, C/C++... Open Source Suporte da Ericsson (pago) Extensa biblioteca OTP (Open Telecom Platform) para suporte à implementações de sistemas de redes e de telecomunicações. Eficiência e confiabilidade bem fundamentada pela indústria de telecomunicações que utilizam Erlang em seu sistemas. Excelente para programação concorrente: a mudança de contexto entre processos Erlang tem uma ordem de magnitude de uma a duas vezes menor do que processos escritos em C. Ótimo suporte à programação de sistemas distribuídos. Código pode ser atualizado sem a necessidade de interromper o programa em execução e permite que o código novo (new) e antigo (old) executem ao mesmo tempo; ideal para sistemas que não podem parar. Possibilidade de utilizar programas escritos em outras linguagens (e.g. Java, C/C++). Alta portabilidade devido à Máquina Virtual: código compilado em uma arquitetura pode rodar em qualquer outra sem necessidade de ajustes. Open Source: ótima gama de documentação, código disponível, baixo custo. Suporte da Ericsson®. Facilidade de aprendizado. Muitas ferramentas disponíveis. Ótima para aplicações matemáticas e prova de propriedades.

52 Desvantagens Desempenho (linguagem interpretada)
Não disponível para muitas plataformas (versão compilada) Fraqueza em programação “baixo nível” Não recomendável em sistemas em que o desempenho é crucial, já que é uma linguagem interpretada. Embora exista o projeto HIPE (High Performance Erlang) no qual o código é compilado para a arquitetura hospedeira, não está disponível para todas as plataformas e está ainda em desenvolvimento. Fraqueza em programação de baixo nível, como por exemplo implementações de device drivers de Sistemas Operacionais. Neste caso, é eclipsada por códigos escritos em C.

53 Roteiro Introdução Histórico Características Utilização Especificação
Implementação e Ambientes de Desenvolvimento Sintaxe Vantagens e Desvantagens Tendências

54 Tendências Open Source Linguagem atualizada
Fácil literatura Baixo Custo Linguagem atualizada Documentações recentes Constantes Releases Futuro promissor com sistemas multi-processados e tendências dos novos processadores “Multi-core” Erlang é uma linguagem que tem muito potencial a ser explorado, pela facilidade de escrever programas sucintos. Além da facilidade conhecida que uma linguagem funcional tem com processamento de informações baseadas em princípios da matemáticaa, deixando mais compreensível a descrição de funções matemáticas e provas de propriedades.   Um fator interessante é a linguagem ser Open Source, o que aumenta a quantidade de especificações e trabalhos relacionados, enriquecendo a literatura sobre a linguagem, que permite programadores optem pela escolha de Erlang para implementação tanto pelas suas características e fatores positivos, como também cases e literatura ampla para tirar dúvidas e compartilhar conhecimento. A literatura oficial, está bastante atualizada, vide o livro Programming Erlang, de Joe Armstrong, lançado neste ano de 2007. Com os atuais processadores Dual Core da Intel e da AMD, e a tendência de lançamentos em breve de processadores multi-core, a linguagem Erlang pode tornar-se uma alternativa bastante interessante para tirar um maior poder de paralelismo e distribuição que os núcleos dos processadores oferecem, deixando os programas escritos nessa linguagem com uma ótima performance em relação às linguagens comumente utilizadas, por ter sido uma linguagem projetada justamente para tratar questões de programação concorrente e distribuída com uma maior eficiência. 

55 Referências Erlang. Wikipedia, the free encyclopedia. Linguagem de Programação Erlang. TNT.br. Armstrong, Joe. Erlang: What´s all this fuss about Erlang?. Open Source Erlang. A History of Erlang. Erlang Reference Manual.

56 Erlang Programming Language
? Dúvidas


Carregar ppt "Erlang Programming Language"

Apresentações semelhantes


Anúncios Google