Misplaced Pages

Erlang (programming language): Difference between revisions

Article snapshot taken from Wikipedia with creative commons attribution-sharealike license. Give it a read and then ask your questions in the chat. We can research this topic together.
Browse history interactively← Previous editContent deleted Content addedVisualWikitext
Revision as of 00:43, 16 June 2015 edit86.82.44.193 (talk) Concurrency and distribution orientation← Previous edit Latest revision as of 20:22, 4 December 2024 edit undoTypoEater (talk | contribs)Extended confirmed users601 editsm Supervisor trees: Removed awkward wording ('secondly' with no corresponding 'firstly') 
(405 intermediate revisions by more than 100 users not shown)
Line 1: Line 1:
{{Short description|Programming language}}
{{about|the programming language|other things named "Erlang"|Erlang (disambiguation)}}
{{Use dmy dates|date=March 2020}}

{{Infobox programming language {{Infobox programming language
| name = Erlang | name = Erlang
| logo = ] | logo = Erlang logo.svg
| logo size = 120px
| paradigm = ]: ], ]
| paradigms = ]: ], ], ]
| year = {{Start date and age|1986}}
| family =
| designer = Joe Armstrong, Robert Virding and Mike Williams
| designer = {{unbulleted list|]|Robert Virding|Mike Williams}}
| developer = ] | developer = ]
| released = {{Start date and age|1986}}
| latest release version = 17.5<ref></ref>
| latest release date = {{Start date and age|2015|04|01}} | latest release version = {{wikidata|property|edit|reference|P348}}
| latest release date = {{start date and age|{{wikidata|qualifier|single|P348|P577}}}}
| typing = ], ]
| typing = ], ]
| scope =
| implementations = Erlang | implementations = Erlang
| dialects = | dialects =
| influenced_by = ], ], ]<ref>http://vimeo.com/97329186 18:30</ref> | influenced_by = ], ],<ref>{{cite web |url=https://vimeo.com/97329186 |title=Joe Armstrong - Functional Programming the Long Road to Enlightenment: a Historical and Personal Narrative |first=N. D. C. |last=Conferences |date=4 June 2014 |publisher=Vimeo}}</ref> ], ]
| influenced = ], ], ], ], ], ], ], ], ] | influenced = ], ],<ref>{{cite web|url=http://radar.oreilly.com/2011/06/clojure-java-lisp-jvm.html|website=radar.oreilly.com|title=Clojure: Lisp meets Java, with a side of Erlang - O'Reilly Radar}}</ref> ], ], ], ], ], ], ],<ref>{{Cite web |url=https://doc.rust-lang.org/reference/influences.html |title=Influences - The Rust Reference |website=The Rust Reference |access-date=2023-04-18}}</ref> ], ]
| file_ext = .erl .hrl | file ext = .erl, .hrl
| license = ]
| license = Erlang Public License 1.1<ref>http://www.erlang.org/about.html</ref>(modified ] 1.0;<ref>{{cite web |url=http://www.erlang.org/EPLICENSE |title=ERLANG PUBLIC LICENSE: Version 1.1 |quote=This Erlang License is a derivative work of the Mozilla Public License, Version 1.0.}}</ref> e.g. "disagreements are settled under Swedish law in English"<ref>http://www.erlang.org/static/download/EPL1x0-explained.html</ref>—] incompatible)
| website = {{URL|https://www.erlang.org}}
| ] = yes
| website = {{url|http://www.erlang.org}}
| wikibooks = Erlang Programming | wikibooks = Erlang Programming
}} }}


'''Erlang''' ({{IPAc-en|ˈ|ɜr|l|æ|ŋ}} {{respell|ER|lang}}) is a ], ], ] ] and ] system. The sequential subset of Erlang is almost a ] (excluding certain BIFs such as those manipulating the process dictionary), with ], ], and ]. It was designed by ] to support distributed, ], ], non-stop applications. It supports ], so that code can be changed without stopping a system.<ref>{{cite web|author=Joe Armstrong, Bjarne Däcker, Thomas Lindgren, Håkan Millroth|title=Open-source Erlang - White Paper|url=http://ftp.sunet.se/pub/lang/erlang/white_paper.html|accessdate=31 July 2011}}</ref> '''Erlang''' ({{IPAc-en|ˈ|ɜr|l|æ|ŋ}} {{respell|UR|lang}}) is a ], ], ] ] ], and a ] ]. The term Erlang is used interchangeably with Erlang/OTP, or ] (OTP), which consists of the Erlang ], several ready-to-use components (OTP) mainly written in Erlang, and a set of ] for Erlang programs.<ref>{{cite web |url=http://erlang.org/doc/system_architecture_intro/sys_arch_intro.html#id58791 |title=Erlang Introduction |website=erlang.org}}</ref>


The Erlang ] is designed for systems with these traits:
While ]s require external library support in most languages, Erlang provides language-level features for creating and managing processes with the aim of simplifying concurrent programming. Though all concurrency is explicit in Erlang, processes communicate using ] instead of shared variables, which removes the need for explicit ] (a locking scheme is still used internally by the ]<ref>{{cite web|title=Lock-free message queue|url=http://erlang.2086793.n4.nabble.com/Lock-free-message-queue-td2550221.html|accessdate=23 December 2013}}</ref>).


*]
The first version was developed by Joe Armstrong, Robert Virding and Mike Williams in 1986.<ref name="hopl">Joe Armstrong, "History of Erlang", in ''HOPL III: Proceedings of the third ACM SIGPLAN conference on History of programming languages'', 2007, ISBN 978-1-59593-766-7</ref> It was originally a proprietary language within Ericsson, but was released as ] in 1998.
*]
*]
*], ] applications
*], where code can be changed without stopping a system.<ref>{{cite web |last1=Armstrong |first1=Joe |last2=Däcker |first2=Bjarne |last3=Lindgren |first3=Thomas |last4=Millroth |first4=Håkan |title=Open-source Erlang – White Paper |url=http://ftp.sunet.se/pub/lang/erlang/white_paper.html|archive-url=https://web.archive.org/web/20111025022940/http://ftp.sunet.se/pub/lang/erlang/white_paper.html |archive-date=25 October 2011 |access-date=31 July 2011}}</ref>

The Erlang ] has ] data, ], and ].<ref>Hitchhiker’s Tour of the BEAM – Robert Virding http://www.erlang-factory.com/upload/presentations/708/HitchhikersTouroftheBEAM.pdf</ref> The sequential subset of the Erlang language supports ], ], and ].

A normal Erlang application is built out of hundreds of small Erlang processes.

It was originally ] within ], developed by ], Robert Virding, and Mike Williams in 1986,<ref name="hopl">{{cite conference |last=Armstrong |first=Joe |title=History of Erlang |work=HOPL III: Proceedings of the third ACM SIGPLAN conference on History of programming languages |date=2007 |isbn=978-1-59593-766-7}}</ref> but was released as ] in 1998.<ref>{{cite web|url=http://www.cio.com/article/3020454/open-source-tools/how-tech-giants-spread-open-source-programming-love.html|title=How tech giants spread open source programming love - CIO.com|date=8 January 2016|access-date=5 September 2016|archive-date=22 February 2019|archive-url=https://web.archive.org/web/20190222070551/https://www.cio.com/article/3020454/open-source-tools/how-tech-giants-spread-open-source-programming-love.html|url-status=dead}}</ref><ref>{{cite web |url=http://www.erlang.se/onlinenews/ErlangOTPos.shtml|archive-url=https://web.archive.org/web/19991009002753/http://www.erlang.se/onlinenews/ErlangOTPos.shtml|url-status=dead|archive-date=9 October 1999 |title=Erlang/OTP Released as Open Source, 1998-12-08}}</ref> Erlang/OTP is supported and maintained by the Open Telecom Platform (OTP) product unit at ].


==History== ==History==
The name ''Erlang'', attributed to Bjarne Däcker, has been presumed by those working on the telephony switches (for whom the language was designed) to be a reference to Danish mathematician and engineer ] and a ] of "Ericsson Language".<ref name="hopl"/><ref>{{cite web |url=http://www.erlang.org/pipermail/erlang-questions/1999-February/000098.html |title=Erlang, the mathematician? |date=February 1999 }}</ref><ref>{{cite web |url=https://foldoc.org/Erlang |title=Free Online Dictionary of Computing: Erlang }}</ref> Erlang was designed with the aim of improving the development of telephony applications.<ref>{{cite web|url=http://erlang.org/course/history.html|title=History of Erlang|website=Erlang.org}}</ref> The initial version of Erlang was implemented in ] and was influenced by the programming language ] used in earlier Ericsson exchanges. By 1988 Erlang had proven that it was suitable for prototyping telephone exchanges, but the Prolog interpreter was far too slow. One group within Ericsson estimated that it would need to be 40 times faster to be suitable for production use. In 1992, work began on the ] virtual machine (VM), which compiles Erlang to C using a mix of natively compiled code and ] to strike a balance between performance and disk space.<ref>{{cite book |last=Armstrong |first=Joe |chapter=The development of Erlang |title=Proceedings of the second ACM SIGPLAN international conference on Functional programming |journal=ACM SIGPLAN Notices |date=August 1997 |volume=32 |issue=8 |pages=196–203 |doi=10.1145/258948.258967 |isbn=0897919181 |s2cid=6821037 }}</ref> According to co-inventor Joe Armstrong, the language went from laboratory product to real applications following the collapse of the next-generation ] named ] in 1995. As a result, Erlang was chosen for the next ] (ATM) exchange ''AXD''.<ref name="hopl"/>
The name "Erlang", attributed to Bjarne Däcker, has been presumed by those working on the telephony switches (for whom the language was designed) to be a reference to Danish mathematician and engineer ] or the ubiquitous use of the ], and (initially at least) simultaneously as a ] of "Ericsson Language".<ref name="hopl"/><ref></ref>


]
Erlang was designed with the aim of improving the development of telephony applications. The initial version of Erlang was implemented in ] and was influenced by the programming language ] used in earlier Ericsson exchanges. According to Armstrong, the language went from lab product to real applications following the collapse of the next-generation ] named ''AXE-N'' in 1995. As a result, Erlang was chosen for the next ] ''AXD''.<ref name="hopl"/>
In February 1998, Ericsson Radio Systems banned the in-house use of Erlang for new products, citing a preference for non-proprietary languages.<ref>{{cite thesis|url=https://cogsys.uni-bamberg.de/team/schmid/uoshp/lehreuos/fp01-www/fp-referate/erlang/bjarnelic.pdf#page=45|title=Concurrent Functional Programming for Telecommunications: A Case Study of Technology Introduction|first=Bjarne|last=Däcker|date=October 2000|publisher=Royal Institute of Technology|page=37}}</ref> The ban caused Armstrong and others to make plans to leave Ericsson.<ref name="questions"/> In March 1998 Ericsson announced the AXD301 switch,<ref name="hopl"/> containing over a million lines of Erlang and reported to achieve a ] of ].<ref>
{{cite web |url=http://www.rabbitmq.com/resources/armstrong.pdf |title=Concurrency Oriented Programming in Erlang |date=9 November 2002}}
</ref> In December 1998, the implementation of Erlang was open-sourced and most of the Erlang team resigned to form a new company, Bluetail AB.<ref name="hopl"/> Ericsson eventually relaxed the ban and re-hired Armstrong in 2004.<ref name="questions">{{cite web |url=http://erlang.org/pipermail/erlang-questions/2006-July/021368.html |title=question about Erlang's future |date=6 July 2010}}</ref>


In 2006, native ] support was added to the runtime system and VM.<ref name="hopl"/>
In 1998 Ericsson announced the AXD301 switch, containing over a million lines of Erlang and reported to achieve an availability of ].<ref>
{{cite web|url=http://ll2.ai.mit.edu/talks/armstrong.pdf|title=Concurrency Oriented Programming in Erlang|date=2 November 2002}}
</ref> Shortly thereafter, Ericsson Radio Systems banned the in-house use of Erlang for new products, citing a preference for non-proprietary languages. The ban caused Armstrong and others to leave Ericsson.<ref name="questions"/> The implementation was open-sourced at the end of the year.<ref name="hopl"/> Ericsson eventually lifted the ban; it re-hired Armstrong in 2004.<ref name="questions">{{cite web|url=http://erlang.org/pipermail/erlang-questions/2006-July/021368.html|title=question about Erlang's future|date=6 July 2010}}</ref>


===Processes===
In 2006, native ] support was added to the runtime system and ].<ref name="hopl"/>
Erlang applications are built of very lightweight Erlang processes in the Erlang runtime system. Erlang processes can be seen as "living" objects (]), with data encapsulation and ], but capable of changing behavior during runtime. The Erlang runtime system provides strict ] between Erlang processes (this includes data and garbage collection, separated individually by each Erlang process) and transparent communication between processes (see ]) on different Erlang nodes (on different hosts).


Joe Armstrong, co-inventor of Erlang, summarized the principles of processes in his ] ]:<ref>{{Cite thesis |last=Armstrong |first=Joe |title=Making reliable distributed systems in the presence of software errors |date=20 November 2003 |degree=DTech |publisher=The Royal Institute of Technology |place=Stockholm, Sweden}}</ref>
As Tim Bray, director of Web Technologies at ], expressed in his keynote at ] in July 2008:

{{cquote|If somebody came to me and wanted to pay me a lot of money to build a large scale message handling system that really had to be up all the time, could never afford to go down for years at a time, I would unhesitatingly choose Erlang to build it in.|15px
*Everything is a process.
}}
*Processes are strongly isolated.
*Process creation and destruction is a lightweight operation.
*Message passing is the only way for processes to interact.
*Processes have unique names.
*If you know the name of a process you can send it a message.
*Processes share no resources.
*Error handling is non-local.
*Processes do what they are supposed to do or fail.

Joe Armstrong remarked in an interview with Rackspace in 2013: "If ] is ']', then Erlang is 'write once, run forever'."<ref>{{cite AV media |last=McGreggor |first=Duncan |date=26 March 2013 |title=Rackspace takes a look at the Erlang programming language for distributed computing |medium=Video |language=en |url=https://www.youtube.com/watch?v=u41GEwIq2mE&t=3m59s | archive-url=https://ghostarchive.org/varchive/youtube/20211211/u41GEwIq2mE| archive-date=2021-12-11 | url-status=live|publisher=Rackspace Studios, SFO |access-date=24 April 2019}}{{cbignore}}</ref>

===Usage===
In 2014, ] reported Erlang was being used in its support nodes, and in ], ] and ] mobile networks worldwide and also by ] and ].<ref>{{cite web |url=http://www.ericsson.com/news/141204-inside-erlang-creator-joe-armstrong-tells-his-story_244099435_c |title=Ericsson |work=Ericsson.com |date=4 December 2014 |access-date=7 April 2018}}</ref>

Erlang is used in ]. As ], director of Web Technologies at ], expressed in his keynote at ] (OSCON) in July 2008:
{{Blockquote|If somebody came to me and wanted to pay me a lot of money to build a large scale message handling system that really had to be up all the time, could never afford to go down for years at a time, I would unhesitatingly choose Erlang to build it in.}}

Erlang is the programming language used to code ].<ref>{{cite web |url=https://www.fastcompany.com/3026758/inside-erlang-the-rare-programming-language-behind-whatsapps-success |title=Inside Erlang, The Rare Programming Language Behind WhatsApp's Success |work=fastcompany.com |date=21 February 2014 |access-date=12 November 2019}}</ref>

It is also the language of choice for ] – an ] messaging server.

] is a programming language that compiles into BEAM byte code (via Erlang Abstract Format).<ref>{{Cite web |title=Erlang/Elixir Syntax: A Crash Course |url=https://elixir-lang.org/crash-course.html |access-date=2022-10-10 |website=elixir-lang.github.com |language=en}}</ref>

Since being released as open source, Erlang has been spreading beyond telecoms, establishing itself in other vertical markets such as FinTech, gaming, healthcare, automotive, Internet of Things and blockchain. Apart from WhatsApp, there are other companies listed as Erlang's success stories, including ] (a MasterCard company), ], ], AdRoll, ], ], ], ], and ].<ref>{{cite web |url=https://www.erlang-solutions.com/blog/which-companies-are-using-erlang-and-why-mytopdogstatus.html |title=Which companies are using Erlang, and why? #MyTopdogStatus |work=erlang-solutions.com |date=11 September 2019 |access-date=15 March 2020}}</ref><ref>{{Cite web |url=https://www.erlang-solutions.com/blog/which-new-companies-are-using-erlang-and-elixir-mytopdogstatus.html |title=Which new companies are using Erlang and Elixir? #MyTopdogStatus |website=erlang-solutions.com |date=2 March 2020 | access-date=2020-06-24}}</ref>


==Functional programming examples== ==Functional programming examples==

An Erlang function that uses recursion to count to ten:<ref>{{cite web|url=http://brikis98.blogspot.se/2012/11/seven-languages-in-seven-weeks-erlang.html|title=Redirecting...|publisher=|accessdate=2 May 2015}}</ref>
===Factorial===
<source lang="erlang">
-module(count_to_ten).
-export().
count_to_ten() -> do_count(0).
do_count(10) -> 10;
do_count(Value) -> do_count(Value + 1).
</source>
A ] algorithm implemented in Erlang: A ] algorithm implemented in Erlang:
<source lang="erlang"> <syntaxhighlight lang="erlang">
-module(fact). % This is the file 'fact.erl', the module and the filename must match -module(fact). % This is the file 'fact.erl', the module and the filename must match
-export(). % This exports the function 'fac' of arity 1 (1 parameter, no type, no name) -export(). % This exports the function 'fac' of arity 1 (1 parameter, no type, no name)


Line 63: Line 93:
% Recursively determine, then return the result % Recursively determine, then return the result
% (note the period . meaning 'endif' or 'function end') % (note the period . meaning 'endif' or 'function end')
%% This function will crash if something other than a positive integer is given. %% This function will crash if anything other than a nonnegative integer is given.
%% It illustrates the “Let it crash” philosophy of Erlang. %% It illustrates the "Let it crash" philosophy of Erlang.
</syntaxhighlight>
</source>


===Fibonacci sequence===
A ] algorithm implemented in Erlang (Note: This is only for demonstrating the Erlang ]. This algorithm is rather slow.<ref>http://www.aquabu.com/2008/02/16/fibonacci-sequence-recursion-in-erlang/</ref>):
<source lang="erlang">
-module(fib). % This is the file 'fib.erl', the module and the filename must match
-export(). % This exports the function 'fib' of arity 1


A tail recursive algorithm that produces the ]:
fib(1) -> 1; % If 1, then return 1, otherwise (note the semicolon ; meaning 'else')
fib(2) -> 1; % If 2, then return 1, otherwise
fib(N) -> fib(N - 2) + fib(N - 1).
</source>


<syntaxhighlight lang="erlang">
A sorting algorithm (similar to ]):
%% The module declaration must match the file name "series.erl"
<source lang="erlang">
-module(series).

%% The export statement contains a list of all those functions that form
%% the module's public API. In this case, this module exposes a single
%% function called fib that takes 1 argument (I.E. has an arity of 1)
%% The general syntax for -export is a list containing the name and
%% arity of each public function
-export().

%% ---------------------------------------------------------------------
%% Public API
%% ---------------------------------------------------------------------

%% Handle cases in which fib/1 receives specific values
%% The order in which these function signatures are declared is a vital
%% part of this module's functionality

%% If fib/1 receives a negative number, then return the atom err_neg_val
%% Normally, such defensive coding is discouraged due to Erlang's 'Let
%% it Crash' philosophy, but here the result would be an infinite loop.
fib(N) when N < 0 -> err_neg_val;

%% If fib/1 is passed precisely the integer 0, then return 0
fib(0) -> 0;

%% For all other values, call the private function fib_int/3 to perform
%% the calculation
fib(N) -> fib_int(N-1, 0, 1).

%% ---------------------------------------------------------------------
%% Private API
%% ---------------------------------------------------------------------

%% If fib_int/3 receives 0 as its first argument, then we're done, so
%% return the value in argument B. The second argument is denoted _ to
%% to disregard its value.
fib_int(0, _, B) -> B;

%% For all other argument combinations, recursively call fib_int/3
%% where each call does the following:
%% - decrement counter N
%% - pass the third argument as the new second argument
%% - pass the sum of the second and third arguments as the new
%% third argument
fib_int(N, A, B) -> fib_int(N-1, B, A+B).
</syntaxhighlight>

Omitting the comments gives a much shorter program.

<syntaxhighlight lang="erlang">
-module(series).
-export().

fib(N) when N < 0 -> err_neg_val;
fib(0) -> 0;
fib(N) -> fib_int(N-1, 0, 1).

fib_int(0, _, B) -> B;
fib_int(N, A, B) -> fib_int(N-1, B, A+B).
</syntaxhighlight>

===Quicksort===
] in Erlang, using ]:<ref>{{cite web |url=http://erlang.org/doc/programming_examples/list_comprehensions.html |title=Erlang – List Comprehensions |website=erlang.org}}</ref>

<syntaxhighlight lang="erlang">
%% qsort:qsort(List) %% qsort:qsort(List)
%% Sort a list of items %% Sort a list of items
Line 88: Line 177:
% Compose recursively a list with 'Front' for all elements that should be before 'Pivot' % Compose recursively a list with 'Front' for all elements that should be before 'Pivot'
% then 'Pivot' then 'Back' for all elements that should be after 'Pivot' % then 'Pivot' then 'Back' for all elements that should be after 'Pivot'
qsort() qsort() ++
++ ++ ++
qsort(). qsort().
</syntaxhighlight>
</source>


The above example recursively invokes the function <code>qsort</code> until nothing remains to be sorted. The expression <code></code> is a ], meaning “Construct a list of elements <code>Front</code> such that <code>Front</code> is a member of <code>Rest</code>, and <code>Front</code> is less than <code>Pivot</code>. <code>++</code> is the list concatenation operator. The above example recursively invokes the function <code>qsort</code> until nothing remains to be sorted. The expression <code></code> is a ], meaning "Construct a list of elements <code>Front</code> such that <code>Front</code> is a member of <code>Rest</code>, and <code>Front</code> is less than <code>Pivot</code>." <code>++</code> is the list concatenation operator.


A comparison function can be used for more complicated structures for the sake of readability. A comparison function can be used for more complicated structures for the sake of readability.


The following code would sort lists according to length: The following code would sort lists according to length:
<source lang="erlang"> <syntaxhighlight lang="erlang">
% This is file 'listsort.erl' (the compiler is made this way) % This is file 'listsort.erl' (the compiler is made this way)
-module(listsort). -module(listsort).
Line 114: Line 203:
++ ++ ++ ++
qsort(, Smaller). qsort(, Smaller).
</syntaxhighlight>
</source>


Here again, a <code>Pivot</code> is taken from the first parameter given to <code>qsort()</code> and the rest of <code>Lists</code> is named <code>Rest</code>. Note that the expression A <code>Pivot</code> is taken from the first parameter given to <code>qsort()</code> and the rest of <code>Lists</code> is named <code>Rest</code>. Note that the expression


<source lang="erlang"></source> <syntaxhighlight lang="erlang"></syntaxhighlight>


is no different in form from is no different in form from


<source lang="erlang"></source> <syntaxhighlight lang="erlang"></syntaxhighlight>


(in the previous example) except for the use of a comparison function in the last part, saying “Construct a list of elements <code>X</code> such that <code>X</code> is a member of <code>Rest</code>, and <code>Smaller</code> is true", with <code>Smaller</code> being defined earlier as (in the previous example) except for the use of a comparison function in the last part, saying "Construct a list of elements <code>X</code> such that <code>X</code> is a member of <code>Rest</code>, and <code>Smaller</code> is true", with <code>Smaller</code> being defined earlier as


<source lang="erlang">fun(A,B) -> length(A) < length(B) end</source> <syntaxhighlight lang="erlang">fun(A,B) -> length(A) < length(B) end</syntaxhighlight>


Note also that the ] is named <code>Smaller</code> in the parameter list of the second definition of <code>qsort</code> so that it can be referenced by that name within that function. It is not named in the first definition of <code>qsort</code>, which deals with the base case of an empty list and thus has no need of this function, let alone a name for it. The ] is named <code>Smaller</code> in the parameter list of the second definition of <code>qsort</code> so that it can be referenced by that name within that function. It is not named in the first definition of <code>qsort</code>, which deals with the base case of an empty list and thus has no need of this function, let alone a name for it.


==Data types== ==Data types==
Erlang has eight primitive ]s: Erlang has eight primitive ]s:

;Integers: Integers are written as sequences of decimal digits, for example, 12, 12375 and -23427 are integers. Integer arithmetic is exact and only limited by available memory on the machine. (This is called ].) ;Integers: Integers are written as sequences of decimal digits, for example, 12, 12375 and -23427 are integers. Integer arithmetic is exact and only limited by available memory on the machine. (This is called ].)
;Atoms: Atoms are used within a program to denote distinguished values. They are written as strings of consecutive alphanumeric characters, the first character being lowercase. Atoms can contain any character if they are enclosed within single quotes and an escape convention exists which allows any character to be used within an atom. ;Atoms: Atoms are used within a program to denote distinguished values. They are written as strings of consecutive alphanumeric characters, the first character being lowercase. Atoms can contain any character if they are enclosed within single quotes and an escape convention exists which allows any character to be used within an atom. Atoms are never garbage collected and should be used with caution, especially if using dynamic atom generation.
;Floats: Floating point numbers use the ]. ;Floats: Floating point numbers use the ].
;References: References are globally unique symbols whose only property is that they can be compared for equality. They are created by evaluating the Erlang primitive <code>make_ref()</code>. ;References: References are globally unique symbols whose only property is that they can be compared for equality. They are created by evaluating the Erlang primitive <code>make_ref()</code>.
;Binaries: A binary is a sequence of bytes. Binaries provide a space-efficient way of storing binary data. Erlang primitives exist for composing and decomposing binaries and for efficient input/output of binaries. ;Binaries: A binary is a sequence of bytes. Binaries provide a space-efficient way of storing binary data. Erlang primitives exist for composing and decomposing binaries and for efficient input/output of binaries.
;Pids: Pid is short for ''process identifier''—a Pid is created by the Erlang primitive <code>spawn(...)</code> Pids are references to Erlang processes. ;Pids: Pid is short for ''process identifier''{{snd}}a Pid is created by the Erlang primitive <code>spawn(...)</code> Pids are references to Erlang processes.
;Ports: Ports are used to communicate with the external world. Ports are created with the built-in ] (BIF) <code>open_port</code>. Messages can be sent to and received from ports, but these messages must obey the so-called "port protocol." ;Ports: Ports are used to communicate with the external world. Ports are created with the built-in function <code>open_port</code>. Messages can be sent to and received from ports, but these messages must obey the so-called "port protocol."
;Funs: Funs are function closures. Funs are created by expressions of the form: <code>fun(...) -> ... end</code>. ;Funs: Funs are function ]. Funs are created by expressions of the form: <code>fun(...) -> ... end</code>.

And three compound data types:


And two compound data types:
;Tuples: Tuples are containers for a fixed number of Erlang data types. The syntax <code>{D1,D2,...,Dn}</code> denotes a tuple whose arguments are <code>D1, D2, ... Dn.</code> The arguments can be primitive data types or compound data types. Any element of a tuple can be accessed in constant time. ;Tuples: Tuples are containers for a fixed number of Erlang data types. The syntax <code>{D1,D2,...,Dn}</code> denotes a tuple whose arguments are <code>D1, D2, ... Dn.</code> The arguments can be primitive data types or compound data types. Any element of a tuple can be accessed in constant time.
;Lists: Lists are containers for a variable number of Erlang data types. The syntax <code></code> denotes a list whose first element is <code>Dh</code>, and whose remaining elements are the list <code>Dt</code>. The syntax <code></code> denotes an empty list. The syntax <code></code> is short for <code>]]]</code>. The first element of a list can be accessed in constant time. The first element of a list is called the ''head'' of the list. The remainder of a list when its head has been removed is called the ''tail'' of the list. ;Lists: Lists are containers for a variable number of Erlang data types. The syntax <code></code> denotes a list whose first element is <code>Dh</code>, and whose remaining elements are the list <code>Dt</code>. The syntax <code></code> denotes an empty list. The syntax <code></code> is short for <code>]]]</code>. The first element of a list can be accessed in constant time. The first element of a list is called the ''head'' of the list. The remainder of a list when its head has been removed is called the ''tail'' of the list.
;Maps: Maps contain a variable number of key-value associations. The syntax is<code>#{Key1=>Value1,...,KeyN=>ValueN}</code>.


Two forms of ] are provided: Two forms of ] are provided:

;Strings: Strings are written as doubly quoted lists of characters. This is syntactic sugar for a list of the integer ] codes for the characters in the string. Thus, for example, the string "cat" is shorthand for <code></code>. It has partial support for Unicode strings.<ref>{{cite web|url=http://erlang.org/doc/apps/stdlib/unicode_usage.html|title=Erlang -- Using Unicode in Erlang|publisher=|accessdate=2 May 2015}}</ref>
;Strings: Strings are written as doubly quoted lists of characters. This is syntactic sugar for a list of the integer ] code points for the characters in the string. Thus, for example, the string "cat" is shorthand for <code></code>.<ref>{{cite web |url=http://erlang.org/doc/apps/stdlib/unicode_usage.html#string-and-character-literals |title=String and Character Literals |access-date=2 May 2015}}</ref>
;Records: Records provide a convenient way for associating a tag with each of the elements in a tuple. This allows one to refer to an element of a tuple by name and not by position. A pre-compiler takes the record definition and replaces it with the appropriate tuple reference. ;Records: Records provide a convenient way for associating a tag with each of the elements in a tuple. This allows one to refer to an element of a tuple by name and not by position. A pre-compiler takes the record definition and replaces it with the appropriate tuple reference.


Erlang has no method of defining classes, although there are external libraries available.<ref>{{cite web|url=https://code.google.com/p/ect/|title=ect - Erlang has no method to define classes, although there are external ] available.<ref>{{cite web |url=https://code.google.com/p/ect/ |title=ect – Erlang Class Transformation – add object-oriented programming to Erlang – Google Project Hosting |access-date=2 May 2015}}</ref>

=="Let it crash" coding style==

Erlang Class Transformation - add object-oriented programming to Erlang - Google Project Hosting|publisher=|accessdate=2 May 2015}}</ref>
Erlang is designed with a mechanism that makes it easy for external processes to monitor for crashes (or hardware failures), rather than an in-process mechanism like ] used in many other programming languages. Crashes are reported like other messages, which is the only way processes can communicate with each other,<ref name=Verraes>{{Cite web|last=Verraes|first=Mathias|date=2014-12-09|title=Let It Crash|url=https://verraes.net/2014/12/erlang-let-it-crash/|access-date=2021-02-10|website=Mathias Verraes' Blog|language=en}}</ref> and subprocesses can be spawned cheaply (see ]). The "let it crash" philosophy prefers that a process be completely restarted rather than trying to recover from a serious failure.<ref>{{Cite web|title=Reactive Design Patterns —|url=https://www.reactivedesignpatterns.com/patterns/let-it-crash.html|access-date=2021-02-10|website=www.reactivedesignpatterns.com}}</ref> Though it still requires handling of errors, this philosophy results in less code devoted to ] where error-handling code is highly contextual and specific.<ref name=Verraes />

===Supervisor trees===
A typical Erlang application is written in the form of a supervisor tree. This architecture is based on a hierarchy of processes in which the top level process is known as a "supervisor". The supervisor then spawns multiple child processes that act either as workers or more, lower level supervisors. Such hierarchies can exist to arbitrary depths and have proven to provide a highly scalable and fault-tolerant environment within which application functionality can be implemented.

Within a supervisor tree, all supervisor processes are responsible for managing the lifecycle of their child processes, and this includes handling situations in which those child processes crash. Any process can become a supervisor by first spawning a child process, then calling <code>erlang:monitor/2</code> on that process. If the monitored process then crashes, the supervisor will receive a message containing a tuple whose first member is the atom <code>'DOWN'</code>. The supervisor is responsible firstly for listening for such messages and for taking the appropriate action to correct the error condition.


==Concurrency and distribution orientation== ==Concurrency and distribution orientation==
Erlang's main strength is support for ]. It has a small but powerful set of primitives to create processes and communicate among them. Erlang is conceptually similar to the ], though it recasts the ideas of ] (CSP) in a functional framework and uses asynchronous message passing.<ref >{{Cite journal Erlang's main strength is support for ]. It has a small but powerful set of primitives to create processes and communicate among them. Erlang is conceptually similar to the language ], though it recasts the ideas of ] (CSP) in a functional framework and uses asynchronous message passing.<ref>{{cite journal
|title=Erlang |title=Erlang
|journal=] |journal=]
|volume=53 |issue=9 |volume=53 |issue=9
|date=September 2010 |date=September 2010
|pages=68-75 |pages=68–75
|doi=10.1145/1810891.1810910 |doi=10.1145/1810891.1810910
|author=Joe Armstrong |first=Joe |last=Armstrong
|authorlink=Joe Armstrong (programming) |author-link=Joe Armstrong (programmer)
|quote=Erlang is conceptually similar to occam programming language, though it recasts the ideas of CSP in a functional framework and uses asynchronous message passing. |quote=Erlang is conceptually similar to the occam programming language, though it recasts the ideas of CSP in a functional framework and uses asynchronous message passing.
|doi-access=free
}}</ref> Processes are the primary means to structure an Erlang application. They are neither operating system ] nor operating system ], but lightweight processes. Like operating system processes (but unlike operating system threads), they share no state with each other. The estimated minimal overhead for each is 300 ].<ref>{{cite web|title=Erlang Efficiency Guide - Processes|url=http://www.erlang.org/doc/efficiency_guide/processes.html}}</ref> Thus, many processes can be created without degrading performance. A benchmark with 20 million processes has been successfully performed.<ref>{{cite web|author=Ulf Wiger|title=Stress-testing erlang| url=http://groups.google.com/group/comp.lang.functional/msg/33b7a62afb727a4f?dmode=source| work=comp.lang.functional.misc|accessdate=25 August 2006|date=14 November 2005}}</ref> Erlang has supported ] since release R11B of May 2006.
}}</ref> Processes are the primary means to structure an Erlang application. They are neither ] ] nor ], but ] that are scheduled by BEAM. Like operating system processes (but unlike operating system threads), they share no state with each other. The estimated minimal overhead for each is 300 ].<ref>{{cite web |title=Erlang Efficiency Guide – Processes |url=http://www.erlang.org/doc/efficiency_guide/processes.html|archive-url=https://web.archive.org/web/20150227174813/http://www.erlang.org/doc/efficiency_guide/processes.html|archive-date=27 February 2015}}</ref> Thus, many processes can be created without degrading performance. In 2005, a benchmark with 20 million processes was successfully performed with 64-bit Erlang on a machine with 16 GB ] (RAM; total 800 bytes/process).<ref>{{cite web |first=Ulf |last=Wiger |title=Stress-testing erlang |url=https://groups.google.com/group/comp.lang.functional/msg/33b7a62afb727a4f?dmode=source |work=comp.lang.functional.misc |access-date=25 August 2006 |date=14 November 2005}}</ref> Erlang has supported ] since release R11B of May 2006.


While ] need external library support in most languages, Erlang provides language-level features to create and manage processes with the goal of simplifying concurrent programming. Though all concurrency is explicit in Erlang, processes communicate using ] instead of shared variables, which removes the need for explicit ] (a locking scheme is still used internally by the VM).<ref>{{cite web |title=Lock-free message queue |url=http://erlang.2086793.n4.nabble.com/Lock-free-message-queue-td2550221.html |access-date=23 December 2013 |archive-date=24 December 2013 |archive-url=https://web.archive.org/web/20131224104549/http://erlang.2086793.n4.nabble.com/Lock-free-message-queue-td2550221.html |url-status=dead }}</ref>
] works via a ] ] ] system: every process has a "mailbox", a ] of messages that have been sent by other processes and not yet consumed. A process uses the <code>receive</code> primitive to retrieve messages that match desired patterns. A message-handling routine tests messages in turn against each pattern, until one of them matches. When the message is consumed and removed from the mailbox the process resumes execution. A message may comprise any Erlang structure, including primitives (integers, floats, characters, atoms), tuples, lists, and functions.

] works via a ] ] ] system: every process has a "mailbox", a ] of messages that have been sent by other processes and not yet consumed. A process uses the <code>receive</code> primitive to retrieve messages that match desired patterns. A message-handling routine tests messages in turn against each pattern, until one of them matches. When the message is consumed and removed from the mailbox the process resumes execution. A message may comprise any Erlang structure, including primitives (integers, floats, characters, atoms), tuples, lists, and functions.


The code example below shows the built-in support for distributed processes: The code example below shows the built-in support for distributed processes:

<source lang="erlang">
<syntaxhighlight lang="erlang">
% Create a process and invoke the function web:start_server(Port, MaxConnections) % Create a process and invoke the function web:start_server(Port, MaxConnections)
ServerProcess = spawn(web, start_server, ), ServerProcess = spawn(web, start_server, ),
Line 189: Line 292:
{goodbye, Text} -> io:format("Got goodbye message: ~s", ) {goodbye, Text} -> io:format("Got goodbye message: ~s", )
end. end.
</syntaxhighlight>
</source>


As the example shows, processes may be created on remote nodes, and communication with them is transparent in the sense that communication with remote processes works exactly as communication with local processes. As the example shows, processes may be created on remote nodes, and communication with them is transparent in the sense that communication with remote processes works exactly as communication with local processes.


Concurrency supports the primary method of error-handling in Erlang. When a process crashes, it neatly exits and sends a message to the controlling process which can take action.<ref>{{cite web|author=Joe Armstrong|title=Erlang robustness|url=http://www.erlang.org/doc/getting_started/robustness.html|accessdate=15 July 2010}}</ref><ref>{{cite web|title=Erlang Supervision principles|url=http://www.erlang.org/doc/design_principles/sup_princ.html|accessdate=15 July 2010}}</ref> Concurrency supports the primary method of error-handling in Erlang. When a process crashes, it neatly exits and sends a message to the controlling process which can then take action, such as starting a new process that takes over the old process's task.<ref>{{cite web |first=Joe |last=Armstrong |title=Erlang robustness |url=http://www.erlang.org/doc/getting_started/robustness.html|archive-url=https://web.archive.org/web/20150423182840/http://www.erlang.org/doc/getting_started/robustness.html|archive-date=23 April 2015 |access-date=15 July 2010}}</ref><ref>{{cite web |title=Erlang Supervision principles |url=http://www.erlang.org/doc/design_principles/sup_princ.html|archive-url=https://web.archive.org/web/20150206050600/http://www.erlang.org/doc/design_principles/sup_princ.html|archive-date=6 February 2015 |access-date=15 July 2010}}</ref>


==Implementation== ==Implementation==
The Ericsson Erlang implementation loads virtual machine ] which is converted to ] at load time. It also includes a native code compiler on most platforms, developed by the High Performance Erlang Project (HiPE) at ]. Since October 2001 the HiPE system is fully integrated in Ericsson's Open Source Erlang/OTP system.<ref>{{cite web|title=High Performance Erlang|url=http://www.it.uu.se/research/group/hipe/|accessdate=26 March 2011}}</ref> It also supports interpreting, directly from source code via ], via script as of R11B-5 release of Erlang. The official reference implementation of Erlang uses ].<ref>{{cite web |url=http://erlang.org/doc/reference_manual/code_loading.html#id90080 |title=Erlang – Compilation and Code Loading |website=erlang.org |access-date=2017-12-21}}</ref> BEAM is included in the official distribution of Erlang, called Erlang/OTP. BEAM executes ] which is converted to ] at load time. It also includes a native code compiler on most platforms, developed by the High Performance Erlang Project (HiPE) at ]. Since October 2001 the HiPE system is fully integrated in Ericsson's Open Source Erlang/OTP system.<ref>{{cite web |title=High Performance Erlang |url=http://www.it.uu.se/research/group/hipe/ |access-date=26 March 2011}}</ref> It also supports interpreting, directly from source code via ], via script as of R11B-5 release of Erlang.


==Hot code loading and modules== ==Hot code loading and modules==
Line 202: Line 305:


An example of the mechanism of hot code loading: An example of the mechanism of hot code loading:

<source lang = "erlang">
<syntaxhighlight lang = "erlang">
%% A process whose only job is to keep a counter. %% A process whose only job is to keep a counter.
%% First version %% First version
Line 223: Line 327:


codeswitch(Sum) -> loop(Sum). codeswitch(Sum) -> loop(Sum).
</syntaxhighlight>
</source>

For the second version, we add the possibility to reset the count to zero. For the second version, we add the possibility to reset the count to zero.

<source lang = "erlang">
<syntaxhighlight lang = "erlang">
%% Second version %% Second version
-module(counter). -module(counter).
Line 246: Line 352:


codeswitch(Sum) -> loop(Sum). codeswitch(Sum) -> loop(Sum).
</syntaxhighlight>
</source>
Only when receiving a message consisting of the atom 'code_switch' will the loop execute an external call to codeswitch/1 (<code>?MODULE</code> is a preprocessor macro for the current module). If there is a new version of the "counter" module in memory, then its codeswitch/1 function will be called. The practice of having a specific entry-point into a new version allows the programmer to transform state to what is required in the newer version. In our example we keep the state as an integer.


Only when receiving a message consisting of the atom <code>code_switch</code> will the loop execute an external call to codeswitch/1 (<code>?MODULE</code> is a preprocessor macro for the current module). If there is a new version of the ''counter'' module in memory, then its codeswitch/1 function will be called. The practice of having a specific entry-point into a new version allows the programmer to transform state to what is needed in the newer version. In the example, the state is kept as an integer.
In practice, systems are built up using design principles from the Open Telecom Platform which leads to more code upgradable designs. Successful hot code loading is a tricky subject; Code needs to be written to make use of Erlang's facilities.

In practice, systems are built up using design principles from the Open Telecom Platform, which leads to more code upgradable designs. Successful hot code loading is exacting. Code must be written with care to make use of Erlang's facilities.


==Distribution== ==Distribution==
In 1998, Ericsson released Erlang as ] to ensure its independence from a single vendor and to increase awareness of the language. Erlang, together with libraries and the real-time distributed database ], forms the ] (OTP) collection of libraries. Ericsson and a few other companies offer commercial support for Erlang. In 1998, Ericsson released Erlang as ] to ensure its independence from a single vendor and to increase awareness of the language. Erlang, together with libraries and the real-time distributed database ], forms the OTP collection of libraries. Ericsson and a few other companies support Erlang commercially.


Since the open source release, Erlang has been used by several firms worldwide, including ] and ].<ref>{{cite web|title=Who uses Erlang for product development?|work=Frequently asked questions about Erlang|url=http://www.erlang.org/faq/faq.html#AEN50|accessdate=16 July 2007|quote=''The largest user of Erlang is (surprise!) Ericsson. Ericsson use it to write software used in telecommunications systems. Many dozens of projects have used it, a particularly large one is the extremely scalable AXD301 ATM switch.'' Other commercial users listed as part of the FAQ include: Nortel, Deutsche Flugsicherung (the German national ] organisation), and T-Mobile.}}</ref> Although Erlang was designed to fill a niche and has remained an obscure language for most of its existence, its popularity is growing due to demand for concurrent services.<ref>{{cite web|title=Programming Erlang|url=http://www.ddj.com/linux-open-source/201001928?cid=RSSfeed_DDJ_OpenSource|accessdate=13 December 2008|quote=Virtually all language use shared state concurrency. This is very difficult and leads to terrible problems when you handle failure and scale up the system...Some pretty fast-moving startups in the financial world have latched onto Erlang; for example, the Swedish www.kreditor.se.}}</ref><ref>{{cite web|title=Erlang, the next Java|url=http://www.cincomsmalltalk.com/userblogs/ralph/blogView?showComments=true&entry=3364027251|accessdate=8 October 2008|quote=I do not believe that other languages can catch up with Erlang anytime soon. It will be easy for them to add language features to be like Erlang. It will take a long time for them to build such a high-quality VM and the mature libraries for concurrency and reliability. So, Erlang is poised for success. If you want to build a multicore application in the next few years, you should look at Erlang.}}</ref> Since the open source release, Erlang has been used by several firms worldwide, including ] and ].<ref>{{cite web |title=Who uses Erlang for product development? |work=Frequently asked questions about Erlang |url=http://erlang.org/faq/introduction.html#idp32141008 |access-date=16 July 2007 |quote=''The largest user of Erlang is (surprise!) Ericsson. Ericsson use it to write software used in telecommunications systems. Many dozens of projects have used it, a particularly large one is the extremely scalable AXD301 ATM switch.'' Other commercial users listed as part of the FAQ include: Nortel, Deutsche Flugsicherung (the German national ] organisation), and T-Mobile.}}</ref> Although Erlang was designed to fill a niche and has remained an obscure language for most of its existence, its popularity is growing due to demand for concurrent services.<ref>{{cite web |title=Programming Erlang |url=http://www.ddj.com/linux-open-source/201001928?cid=RSSfeed_DDJ_OpenSource |access-date=13 December 2008 |quote=Virtually all language use shared state concurrency. This is very difficult and leads to terrible problems when you handle failure and scale up the system...Some pretty fast-moving startups in the financial world have latched onto Erlang; for example, the Swedish www.kreditor.se.}}</ref><ref>{{cite web |title=Erlang, the next Java |url=http://www.cincomsmalltalk.com/userblogs/ralph/blogView?showComments=true&entry=3364027251|archive-url=https://web.archive.org/web/20071011065959/http://cincomsmalltalk.com/userblogs/ralph/blogView?showComments=true&entry=3364027251|url-status=dead|archive-date=11 October 2007 |access-date=8 October 2008 |quote=I do not believe that other languages can catch up with Erlang anytime soon. It will be easy for them to add language features to be like Erlang. It will take a long time for them to build such a high-quality VM and the mature libraries for concurrency and reliability. So, Erlang is poised for success. If you want to build a multicore application in the next few years, you should look at Erlang.}}</ref>
Erlang has found some use in fielding ] servers.<ref>{{cite web Erlang has found some use in fielding ] (MMORPG) servers.<ref>{{cite web
| last = Clarke |last=Clarke
| first = Gavin |first=Gavin
| title = Battlestar Galactica vets needed for online roleplay |title=Battlestar Galactica vets needed for online roleplay
| work = Music and Media |work=Music and Media
| publisher = ] |publisher=]
| date = 5 Feb 2011 |date=5 February 2011
| url = http://www.theregister.co.uk/2011/02/05/battlestar_galactica_mmp/ |url=https://www.theregister.co.uk/2011/02/05/battlestar_galactica_mmp/
|access-date=8 February 2011}}
| doi =
| accessdate = 8 February 2011 }}
</ref> </ref>


==See also==
===Projects using Erlang===
* ] – a functional, concurrent, general-purpose programming language that runs on BEAM
Projects using Erlang include:
* ] - Lua on the BEAM, designed and implemented by one of the creators of Erlang.

* ] (LFE) – a Lisp-based programming language that runs on BEAM
* ]s
* ]
** ], to serve ]s
* ]
** ], to serve ]s
* ]

* Web servers:
** ] web server

* Database (distributed):
** ], a database service based on the company's fork of CouchDB, ]
** ], a document-based database that uses ]
** ] (née Membase), database management system optimized for storing data behind interactive web applications<ref>{{cite web|url=http://blog.couchbase.com/why-membase-uses-erlang|title=Why Membase Uses Erlang|publisher=|accessdate=2 May 2015}}</ref>
** ], a distributed database
** ], a distributed database
** ], a distributed database that is part of ]<ref>{{cite web|url=http://www.satine.org/archives/2007/12/13/amazon-simpledb/|title=satine.org|work=satine.org|accessdate=2 May 2015}}</ref>

* Chat:
** ], an ] (XMPP) instant messaging server
*** ] system was running on ejabberd based servers<ref>{{cite web|url=http://www.facebook.com/note.php?note_id=16787213919&id=9445547199&index=2 |title=Thrift: (slightly more than) one year later |publisher=Facebook.com |date= |accessdate=2013-07-10}}</ref><ref>{{cite web|url=http://developers.facebook.com/news.php?blog=1&story=110 |title=Using Facebook Chat via Jabber- Facebook Developers |publisher=Developers.facebook.com |date= |accessdate=2013-07-10}}</ref><ref>{{cite web|url=http://www.erlang-factory.com/upload/presentations/31/EugeneLetuchy-ErlangatFacebook.pdf |title=Erlang at Facebook - Eugene Letuchy |publisher=Erlang Factory |date= |accessdate=2014-09-18}}</ref>
*** ] chat is based on ejabberd<ref>{{cite web|url=http://blog.tuenti.com/dev/chat-in-the-making/ |title=Chat in the making &#124; Tuenti Corporate |language=es |publisher=Blog.tuenti.com |date=2010-03-17 |accessdate=2013-07-10}}</ref>

* CMS:
** ], a content management system and web framework

* ]:
** ], for which the core API server, originally written in ], was completely re-written in version 11 in Erlang<ref name="chef11">{{cite web|url=http://www.opscode.com/blog/2013/02/04/chef-11-released/|title=Chef 11 Released!|publisher=]|date=4 February 2013}}</ref>

* Queue:
** ], an implementation of ] (AMQP)

* Desktop:
** ], a 3D subdivision modeler, used to model and texture polygon meshes

* Tools
** ], a web-based hosting service for software development projects that use the ] version control system. Erlang is used for RPC proxies to ruby processes.<ref>{{cite web|url=http://www.infoq.com/interviews/erlang-and-github |title=The way GitHub helped Erlang and the way Erlang helped Github |publisher=Infoq.com |date=2010-08-16 |accessdate=2013-07-10}}</ref>

* Mobile:
** ], mobile messenger<ref>{{cite web|url=http://blog.whatsapp.com/index.php/2012/01/1-million-is-so-2011/ |title=1 million is so 2011 |publisher=Blog.whatsapp.com |date=2012-01-06 |accessdate=2013-07-10}}</ref>
** ], an anonymous social network<ref>{{cite web|url=http://inaka.net/case-studies/case-studies-whisper.html|title=inaka / case-studies|author=inaka|publisher=|accessdate=2 May 2015}}</ref>

* Enterprise:
** ], an online digital publisher<ref>{{cite web|author=Af Tania Andersen Onsdag, 26. august 2009 - 8:10 |url=http://www.version2.dk/artikel/saadan-fik-dansk-succes-website-held-med-erlang-og-amazon-11898 |title=Sådan fik dansk succes-website held med Erlang og Amazon &#124; Version2 |language=da |publisher=Version2.dk |date= |accessdate=2013-07-10}}</ref>
** ], a service to view trends and patterns from ]<ref>{{cite web|url=http://twitter.com/jalada/status/1206606823 |title=Twitter / jalada: Twitterfall is now powered |publisher=Twitter.com |date= |accessdate=2013-07-10}}</ref><ref>{{cite web|url=http://twitter.com/jalada/statuses/1234217518 |title=Twitter / jalada: @TacticalGrace Sure does. The |publisher=Twitter.com |date= |accessdate=2013-07-10}}</ref>

* Trading
** ], ] programs
** ], sports ]

* Gaming
** ] Naos game server<ref>{{cite web|url=http://www.guildsoftware.com/naos/inbrief.html |title=The NAOS Engine - In Brief |publisher=Guildsoftware.com |date= |accessdate=2013-07-10}}</ref>
** ] game server by ]
** ] server core<ref>{{cite web |title=Erlang and First-Person Shooters |url=http://www.erlang-factory.com/upload/presentations/395/ErlangandFirst-PersonShooters.pdf |accessdate=9 August 2012 |quote=Presentation about Erlang and ] from ].}}</ref>
** ] chat system by ], based on ejabberd

===Companies using Erlang===
Companies using Erlang in their production systems include:
* ] uses Erlang to implement ], providing database services as a part of the Amazon Web Services offering.{{citation needed|date=August 2012}}
* ] uses it in its social bookmarking service, Delicious, which has more than 5 million users and 150 million bookmarked URLs.{{citation needed|date=August 2012}}
* ] uses Erlang to power the backend of its chat service, handling more than 200 million active users.<ref>http://www.erlang-factory.com/upload/presentations/31/EugeneLetuchy-ErlangatFacebook.pdf</ref> It can be observed in some of its ] headers.
* ] uses Erlang in its SMS and authentication systems.{{citation needed|date=August 2012}}
* ] is using Erlang in call processing products in the public-safety industry.{{citation needed|date=August 2012}}
* ] uses Erlang in its support nodes, used in GPRS and 3G mobile networks worldwide.<ref>{{cite web|url=http://www.ericsson.com/ericsson/corpinfo/publications/review/2000_03/files/2000034.pdf |title=GPRS support notes |publisher=Ericsson.com |accessdate=2013-08-18}}</ref>
* ] uses Erlang in its games.{{Citation needed|date=December 2013}}
* ] uses Erlang to run messaging servers, achieving up to 2 million connected users per server.<ref name="whatsapp.blog.2012"> // WhatsApp blog, 2012-01-06: " the last important piece of our infrastracture is Erlang"</ref><ref name="whatsapp.at.SF.erlang.factory">Rick Reed (WhatsApp), - Erlang Factory SF, March 30, 2012</ref>{{Dubious|date=December 2013}}
* ] uses Erlang for its commenting system on HuffPost Live <ref>{{cite web|url=http://www.huffingtonpost.com/adam-denenberg/huffington-post-engineeri_b_3818148.html |title=Huffington Post Engineering and Erlang |accessdate=2014-01-31}}</ref>
* ] uses Erlang for its distributed file system <ref>{{cite web|url=https://erlangcentral.org/introducing-leofs-the-lion-of-storage-systems |title=Introducing LeoFS – the Lion of Storage Systems}}</ref>
* ] uses Erlang in some of its internal applications to manage networking devices <ref>{{cite web|url=http://www.rackspace.com/blog/how-rackspace-is-using-erlang |title=How Rackspace Is Using Erlang}}</ref>
* ], a Swedish e-commerce company, has been using Erlang to handle 9 million customers and 50 million transaction since 2005.
* ], the online gambling firm uses the language in production to drive its InPlay betting service, pushing live odds of sporting events to millions of customers in near real-time. <ref>{{cite web|url=http://www.techworld.com/apps/how-bet365-solved-reliability-scalability-by-swapping-java-for-erlang-3600737/ |title=Online gambling firm bet365 has swapped Java for Erlang}}</ref>

==Variants==
* : re-implementation with a ]-style syntax.
* ]: a functional, concurrent, general-purpose programming language that runs on the Erlang Virtual Machine (BEAM).


==References== ==References==
{{Reflist|colwidth=30em}} {{Reflist|30em}}


==Further reading== ==Further reading==
{{Refbegin}} {{Refbegin}}
* {{Cite journal|author=Joe Armstrong|title=Making reliable distributed systems in the presence of software errors|url=http://www.sics.se/~joe/thesis/armstrong_thesis_2003.pdf|version=Ph.D. Dissertation|publisher=The Royal Institute of Technology, Stockholm, Sweden|year=2003}} * {{Cite thesis |first=Joe |last=Armstrong |title=Making reliable distributed systems in the presence of software errors |url=https://www.sics.se/~joe/thesis/armstrong_thesis_2003.pdf |type=PhD |publisher=The Royal Institute of Technology, Stockholm, Sweden |year=2003 |access-date=13 February 2016 |url-status=dead |archive-url=https://web.archive.org/web/20150323001245/https://www.sics.se/~joe/thesis/armstrong_thesis_2003.pdf |archive-date=23 March 2015 }}
* {{cite book |doi=10.1145/1238844.1238850 |isbn=978-1-59593-766-7 |title=Proceedings of the third ACM SIGPLAN conference on History of programming languages – HOPL III |year=2007 |chapter=A history of Erlang |last=Armstrong |first=Joe |pages=6–1|s2cid=555765 }}
* {{cite doi|10.1145/1238844.1238850}}
* by Bjarne Däcker * {{Webarchive|url=https://web.archive.org/web/20190829000127/http://www.erlang.se/publications/bjarnelic.pdf |date=29 August 2019 }} by Bjarne Däcker
*{{cite journal|authors=Mattsson, H.; Nilsson, H.; Wikstrom, C.|year=1999|title=Mnesia - A distributed robust DBMS for telecommunications applications|journal=First International Workshop on Practical Aspects of Declarative Languages (PADL '99)|pages=152–163}} *{{cite journal |last1=Mattsson |first1=H. |last2=Nilsson |first2=H. |last3=Wikstrom |first3=C. |year=1999 |title=Mnesia A distributed robust DBMS for telecommunications applications |journal=First International Workshop on Practical Aspects of Declarative Languages (PADL '99) |pages=152–163}}
* {{cite book * {{cite book
| first1 = Joe |first1=Joe
| last1 = Armstrong |last1=Armstrong
| first2 = Robert |first2=Robert
| last2 = Virding |last2=Virding
| first3 = Mike |first3=Mike
| last3 = Williams |last3=Williams
| first4 = Claes |first4=Claes
| last4 = Wikstrom |last4=Wikstrom
| title = Concurrent Programming in Erlang |title=Concurrent Programming in Erlang
| publisher = ] |publisher=]
| edition = 2nd |edition=2nd
| date = 16 January 1996 |date=16 January 1996
| page = 358 |page=358
| isbn = 978-0-13-508301-7 |isbn=978-0-13-508301-7
| url = http://www.erlang.org/erlang_book_toc.html |url=http://www.erlang.org/erlang_book_toc.html
|archive-url=https://web.archive.org/web/20120306002430/http://www.erlang.org/erlang_book_toc.html
}}
|archive-date=6 March 2012
}}
* {{cite book * {{cite book
| first1 = Joe |first=Joe
| last1 = Armstrong |last=Armstrong
| title = Programming Erlang: Software for a Concurrent World |title=Programming Erlang: Software for a Concurrent World
| publisher = ] |publisher=]
| edition = 1st |edition=1st
| date = 11 July 2007 |date=11 July 2007
|page=
| page = 536
| isbn = 978-1-934356-00-5 |isbn=978-1-934356-00-5
|url=https://archive.org/details/programmingerlan0000arms/page/536
| url = http://pragprog.com/titles/jaerlang/programming-erlang
|url-access=registration
}}
}}
* {{cite book * {{cite book
| first1 = Simon J. |first1=Simon J.
| last1 = Thompson |last1=Thompson
| first2 = Francesco |first2=Francesco
| last2 = Cesarini |last2=Cesarini
| title = Erlang Programming: A Concurrent Approach to Software Development |title=Erlang Programming: A Concurrent Approach to Software Development
| publisher = ], Inc |publisher=], Inc.
| edition = 1st |edition=1st
| date = 19 June 2009 |date=19 June 2009
| page = 496 |page=496
| location = Sebastopol, California |location=Sebastopol, California
| isbn = 978-0-596-51818-9 |isbn=978-0-596-51818-9
| url = http://www.erlangprogramming.org |url=http://www.erlangprogramming.org
}} }}
* {{cite book * {{cite book
| first1 = Martin |first1=Martin
| last1 = Logan |last1=Logan
| first2 = Eric |first2=Eric
| last2 = Merritt |last2=Merritt
| first3 = Richard |first3=Richard
| last3 = Carlsson |last3=Carlsson
| title = Erlang and OTP in Action |title=Erlang and OTP in Action
| publisher = ] |publisher=]
| edition = 1st |edition=1st
| date = 28 May 2010 |date=28 May 2010
| page = 500 |page=500
| location = Greenwich, CT |location=Greenwich, CT
| isbn = 978-1-933988-78-8 |isbn=978-1-933988-78-8
}}
| url =
}}
* {{cite web * {{cite web
| last = Martin |last=Martin
| first = Brown |first=Brown
| title = Introduction to programming in Erlang, Part 1: The basics |title=Introduction to programming in Erlang, Part 1: The basics
| work = developerWorks |work=developerWorks
| publisher = IBM |publisher=IBM
| date = 10 May 2011 |date=10 May 2011
| url = http://www.ibm.com/developerworks/opensource/library/os-erlang1/index.html |url=http://www.ibm.com/developerworks/opensource/library/os-erlang1/index.html
| accessdate =10 May 2011 |access-date=10 May 2011
}} }}
* {{cite web * {{cite web
| last = Martin |last=Martin
| first = Brown |first=Brown
| title = Introduction to programming in Erlang, Part 2: Use advanced features and functionality |title=Introduction to programming in Erlang, Part 2: Use advanced features and functionality
| work = developerWorks |work=developerWorks
| publisher = IBM |publisher=IBM
| date = 17 May 2011 |date=17 May 2011
| url = http://www.ibm.com/developerworks/opensource/library/os-erlang2/index.html |url=http://www.ibm.com/developerworks/opensource/library/os-erlang2/index.html
| accessdate =17 May 2011}} |access-date=17 May 2011
}}
* {{cite web * {{cite web
| last = Wiger |last=Wiger
| first = Ulf |first=Ulf
| title = Four-fold Increase in Productivity and Quality: Industrial-Strength Functional Programming in Telecom-Class Products |title=Four-fold Increase in Productivity and Quality: Industrial-Strength Functional Programming in Telecom-Class Products
| work = FEmSYS 2001 Deployment on distributed architectures |work=FEmSYS 2001 Deployment on distributed architectures
| publisher = Ericsson Telecom AB |publisher=Ericsson Telecom AB
| date = 30 Mar 2001 |date=30 March 2001
| url = http://www.erlang.se/publications/Ulf_Wiger.pdf |url=http://www.erlang.se/publications/Ulf_Wiger.pdf
| accessdate =16 Sep 2014 |access-date=16 September 2014
|archive-date=19 August 2019
}}
|archive-url=https://web.archive.org/web/20190819130310/http://www.erlang.se/publications/Ulf_Wiger.pdf
|url-status=dead
}}
{{Refend}} {{Refend}}


Line 444: Line 488:
{{Commons category}} {{Commons category}}
{{Wikibooks|Erlang Programming}} {{Wikibooks|Erlang Programming}}
* ]
*{{Official website}}
* {{Official website}}
*
*, Erlang community site
*, an annual conference focused on Erlang, held in Stockholm, Sweden
*{{dmoz|Computers/Programming/Languages/Erlang|Erlang}}
*, site with much Erlang/OTP information
*
*, tutorial for beginners
*, alternative topic documentation
*, Software Engineering Radio Podcast


{{Programming languages}}
{{use dmy dates|date=January 2012}}
{{Authority control}}


{{DEFAULTSORT:Erlang (Programming Language)}} ]
]
]
] ]
]
]
]
]
] ]
] ]
] ]
]
] ]
]
]
]
]
]
]

Latest revision as of 20:22, 4 December 2024

Programming language

Erlang
ParadigmsMulti-paradigm: concurrent, functional, object oriented
Designed by
DeveloperEricsson
First appeared1986; 38 years ago (1986)
Stable release27.2 Edit this on Wikidata / 11 December 2024; 15 days ago (11 December 2024)
Typing disciplineDynamic, strong
LicenseApache License 2.0
Filename extensions.erl, .hrl
Websitewww.erlang.org
Major implementations
Erlang
Influenced by
Lisp, PLEX, Prolog, Smalltalk
Influenced
Akka, Clojure, Dart, Elixir, F#, Opa, Oz, Reia, Rust, Scala, Go

Erlang (/ˈɜːrlæŋ/ UR-lang) is a general-purpose, concurrent, functional high-level programming language, and a garbage-collected runtime system. The term Erlang is used interchangeably with Erlang/OTP, or Open Telecom Platform (OTP), which consists of the Erlang runtime system, several ready-to-use components (OTP) mainly written in Erlang, and a set of design principles for Erlang programs.

The Erlang runtime system is designed for systems with these traits:

The Erlang programming language has immutable data, pattern matching, and functional programming. The sequential subset of the Erlang language supports eager evaluation, single assignment, and dynamic typing.

A normal Erlang application is built out of hundreds of small Erlang processes.

It was originally proprietary software within Ericsson, developed by Joe Armstrong, Robert Virding, and Mike Williams in 1986, but was released as free and open-source software in 1998. Erlang/OTP is supported and maintained by the Open Telecom Platform (OTP) product unit at Ericsson.

History

The name Erlang, attributed to Bjarne Däcker, has been presumed by those working on the telephony switches (for whom the language was designed) to be a reference to Danish mathematician and engineer Agner Krarup Erlang and a syllabic abbreviation of "Ericsson Language". Erlang was designed with the aim of improving the development of telephony applications. The initial version of Erlang was implemented in Prolog and was influenced by the programming language PLEX used in earlier Ericsson exchanges. By 1988 Erlang had proven that it was suitable for prototyping telephone exchanges, but the Prolog interpreter was far too slow. One group within Ericsson estimated that it would need to be 40 times faster to be suitable for production use. In 1992, work began on the BEAM virtual machine (VM), which compiles Erlang to C using a mix of natively compiled code and threaded code to strike a balance between performance and disk space. According to co-inventor Joe Armstrong, the language went from laboratory product to real applications following the collapse of the next-generation AXE telephone exchange named AXE-N in 1995. As a result, Erlang was chosen for the next Asynchronous Transfer Mode (ATM) exchange AXD.

Robert Virding and Joe Armstrong, 2013

In February 1998, Ericsson Radio Systems banned the in-house use of Erlang for new products, citing a preference for non-proprietary languages. The ban caused Armstrong and others to make plans to leave Ericsson. In March 1998 Ericsson announced the AXD301 switch, containing over a million lines of Erlang and reported to achieve a high availability of nine "9"s. In December 1998, the implementation of Erlang was open-sourced and most of the Erlang team resigned to form a new company, Bluetail AB. Ericsson eventually relaxed the ban and re-hired Armstrong in 2004.

In 2006, native symmetric multiprocessing support was added to the runtime system and VM.

Processes

Erlang applications are built of very lightweight Erlang processes in the Erlang runtime system. Erlang processes can be seen as "living" objects (object-oriented programming), with data encapsulation and message passing, but capable of changing behavior during runtime. The Erlang runtime system provides strict process isolation between Erlang processes (this includes data and garbage collection, separated individually by each Erlang process) and transparent communication between processes (see Location transparency) on different Erlang nodes (on different hosts).

Joe Armstrong, co-inventor of Erlang, summarized the principles of processes in his PhD thesis:

  • Everything is a process.
  • Processes are strongly isolated.
  • Process creation and destruction is a lightweight operation.
  • Message passing is the only way for processes to interact.
  • Processes have unique names.
  • If you know the name of a process you can send it a message.
  • Processes share no resources.
  • Error handling is non-local.
  • Processes do what they are supposed to do or fail.

Joe Armstrong remarked in an interview with Rackspace in 2013: "If Java is 'write once, run anywhere', then Erlang is 'write once, run forever'."

Usage

In 2014, Ericsson reported Erlang was being used in its support nodes, and in GPRS, 3G and LTE mobile networks worldwide and also by Nortel and Deutsche Telekom.

Erlang is used in RabbitMQ. As Tim Bray, director of Web Technologies at Sun Microsystems, expressed in his keynote at O'Reilly Open Source Convention (OSCON) in July 2008:

If somebody came to me and wanted to pay me a lot of money to build a large scale message handling system that really had to be up all the time, could never afford to go down for years at a time, I would unhesitatingly choose Erlang to build it in.

Erlang is the programming language used to code WhatsApp.

It is also the language of choice for Ejabberd – an XMPP messaging server.

Elixir is a programming language that compiles into BEAM byte code (via Erlang Abstract Format).

Since being released as open source, Erlang has been spreading beyond telecoms, establishing itself in other vertical markets such as FinTech, gaming, healthcare, automotive, Internet of Things and blockchain. Apart from WhatsApp, there are other companies listed as Erlang's success stories, including Vocalink (a MasterCard company), Goldman Sachs, Nintendo, AdRoll, Grindr, BT Mobile, Samsung, OpenX, and SITA.

Functional programming examples

Factorial

A factorial algorithm implemented in Erlang:

-module(fact). % This is the file 'fact.erl', the module and the filename must match
-export(). % This exports the function 'fac' of arity 1 (1 parameter, no type, no name)
fac(0) -> 1; % If 0, then return 1, otherwise (note the semicolon ; meaning 'else')
fac(N) when N > 0, is_integer(N) -> N * fac(N-1).
% Recursively determine, then return the result
% (note the period . meaning 'endif' or 'function end')
%% This function will crash if anything other than a nonnegative integer is given.
%% It illustrates the "Let it crash" philosophy of Erlang.

Fibonacci sequence

A tail recursive algorithm that produces the Fibonacci sequence:

%% The module declaration must match the file name "series.erl" 
-module(series).
%% The export statement contains a list of all those functions that form
%% the module's public API.  In this case, this module exposes a single
%% function called fib that takes 1 argument (I.E. has an arity of 1)
%% The general syntax for -export is a list containing the name and
%% arity of each public function
-export().
%% ---------------------------------------------------------------------
%% Public API
%% ---------------------------------------------------------------------
%% Handle cases in which fib/1 receives specific values
%% The order in which these function signatures are declared is a vital
%% part of this module's functionality
%% If fib/1 receives a negative number, then return the atom err_neg_val
%% Normally, such defensive coding is discouraged due to Erlang's 'Let
%% it Crash' philosophy, but here the result would be an infinite loop.
fib(N) when N < 0 -> err_neg_val;
%% If fib/1 is passed precisely the integer 0, then return 0
fib(0) -> 0;
%% For all other values, call the private function fib_int/3 to perform
%% the calculation
fib(N) -> fib_int(N-1, 0, 1).
%% ---------------------------------------------------------------------
%% Private API
%% ---------------------------------------------------------------------
%% If fib_int/3 receives 0 as its first argument, then we're done, so
%% return the value in argument B. The second argument is denoted _ to
%% to disregard its value.
fib_int(0, _, B) -> B;
%% For all other argument combinations, recursively call fib_int/3
%% where each call does the following:
%%  - decrement counter N
%%  - pass the third argument as the new second argument
%%  - pass the sum of the second and third arguments as the new
%%    third argument
fib_int(N, A, B) -> fib_int(N-1, B, A+B).

Omitting the comments gives a much shorter program.

-module(series).
-export().
fib(N) when N < 0 -> err_neg_val;
fib(0) -> 0;
fib(N) -> fib_int(N-1, 0, 1).
fib_int(0, _, B) -> B;
fib_int(N, A, B) -> fib_int(N-1, B, A+B).

Quicksort

Quicksort in Erlang, using list comprehension:

%% qsort:qsort(List)
%% Sort a list of items
-module(qsort).     % This is the file 'qsort.erl'
-export(). % A function 'qsort' with 1 parameter is exported (no type, no name)
qsort() -> ; % If the list  is empty, return an empty list (nothing to sort)
qsort() ->
    % Compose recursively a list with 'Front' for all elements that should be before 'Pivot'
    % then 'Pivot' then 'Back' for all elements that should be after 'Pivot'
    qsort() ++ 
     ++
    qsort().

The above example recursively invokes the function qsort until nothing remains to be sorted. The expression is a list comprehension, meaning "Construct a list of elements Front such that Front is a member of Rest, and Front is less than Pivot." ++ is the list concatenation operator.

A comparison function can be used for more complicated structures for the sake of readability.

The following code would sort lists according to length:

% This is file 'listsort.erl' (the compiler is made this way)
-module(listsort).
% Export 'by_length' with 1 parameter (don't care about the type and name)
-export().
by_length(Lists) -> % Use 'qsort/2' and provides an anonymous function as a parameter
   qsort(Lists, fun(A,B) -> length(A) < length(B) end).
qsort(, _)-> ; % If list is empty, return an empty list (ignore the second parameter)
qsort(, Smaller) ->
    % Partition list with 'Smaller' elements in front of 'Pivot' and not-'Smaller' elements
    % after 'Pivot' and sort the sublists.
    qsort(, Smaller)
    ++  ++
    qsort(, Smaller).

A Pivot is taken from the first parameter given to qsort() and the rest of Lists is named Rest. Note that the expression


is no different in form from


(in the previous example) except for the use of a comparison function in the last part, saying "Construct a list of elements X such that X is a member of Rest, and Smaller is true", with Smaller being defined earlier as

fun(A,B) -> length(A) < length(B) end

The anonymous function is named Smaller in the parameter list of the second definition of qsort so that it can be referenced by that name within that function. It is not named in the first definition of qsort, which deals with the base case of an empty list and thus has no need of this function, let alone a name for it.

Data types

Erlang has eight primitive data types:

Integers
Integers are written as sequences of decimal digits, for example, 12, 12375 and -23427 are integers. Integer arithmetic is exact and only limited by available memory on the machine. (This is called arbitrary-precision arithmetic.)
Atoms
Atoms are used within a program to denote distinguished values. They are written as strings of consecutive alphanumeric characters, the first character being lowercase. Atoms can contain any character if they are enclosed within single quotes and an escape convention exists which allows any character to be used within an atom. Atoms are never garbage collected and should be used with caution, especially if using dynamic atom generation.
Floats
Floating point numbers use the IEEE 754 64-bit representation.
References
References are globally unique symbols whose only property is that they can be compared for equality. They are created by evaluating the Erlang primitive make_ref().
Binaries
A binary is a sequence of bytes. Binaries provide a space-efficient way of storing binary data. Erlang primitives exist for composing and decomposing binaries and for efficient input/output of binaries.
Pids
Pid is short for process identifier – a Pid is created by the Erlang primitive spawn(...) Pids are references to Erlang processes.
Ports
Ports are used to communicate with the external world. Ports are created with the built-in function open_port. Messages can be sent to and received from ports, but these messages must obey the so-called "port protocol."
Funs
Funs are function closures. Funs are created by expressions of the form: fun(...) -> ... end.

And three compound data types:

Tuples
Tuples are containers for a fixed number of Erlang data types. The syntax {D1,D2,...,Dn} denotes a tuple whose arguments are D1, D2, ... Dn. The arguments can be primitive data types or compound data types. Any element of a tuple can be accessed in constant time.
Lists
Lists are containers for a variable number of Erlang data types. The syntax denotes a list whose first element is Dh, and whose remaining elements are the list Dt. The syntax denotes an empty list. The syntax is short for ]]]. The first element of a list can be accessed in constant time. The first element of a list is called the head of the list. The remainder of a list when its head has been removed is called the tail of the list.
Maps
Maps contain a variable number of key-value associations. The syntax is#{Key1=>Value1,...,KeyN=>ValueN}.

Two forms of syntactic sugar are provided:

Strings
Strings are written as doubly quoted lists of characters. This is syntactic sugar for a list of the integer Unicode code points for the characters in the string. Thus, for example, the string "cat" is shorthand for .
Records
Records provide a convenient way for associating a tag with each of the elements in a tuple. This allows one to refer to an element of a tuple by name and not by position. A pre-compiler takes the record definition and replaces it with the appropriate tuple reference.

Erlang has no method to define classes, although there are external libraries available.

"Let it crash" coding style

Erlang is designed with a mechanism that makes it easy for external processes to monitor for crashes (or hardware failures), rather than an in-process mechanism like exception handling used in many other programming languages. Crashes are reported like other messages, which is the only way processes can communicate with each other, and subprocesses can be spawned cheaply (see below). The "let it crash" philosophy prefers that a process be completely restarted rather than trying to recover from a serious failure. Though it still requires handling of errors, this philosophy results in less code devoted to defensive programming where error-handling code is highly contextual and specific.

Supervisor trees

A typical Erlang application is written in the form of a supervisor tree. This architecture is based on a hierarchy of processes in which the top level process is known as a "supervisor". The supervisor then spawns multiple child processes that act either as workers or more, lower level supervisors. Such hierarchies can exist to arbitrary depths and have proven to provide a highly scalable and fault-tolerant environment within which application functionality can be implemented.

Within a supervisor tree, all supervisor processes are responsible for managing the lifecycle of their child processes, and this includes handling situations in which those child processes crash. Any process can become a supervisor by first spawning a child process, then calling erlang:monitor/2 on that process. If the monitored process then crashes, the supervisor will receive a message containing a tuple whose first member is the atom 'DOWN'. The supervisor is responsible firstly for listening for such messages and for taking the appropriate action to correct the error condition.

Concurrency and distribution orientation

Erlang's main strength is support for concurrency. It has a small but powerful set of primitives to create processes and communicate among them. Erlang is conceptually similar to the language occam, though it recasts the ideas of communicating sequential processes (CSP) in a functional framework and uses asynchronous message passing. Processes are the primary means to structure an Erlang application. They are neither operating system processes nor threads, but lightweight processes that are scheduled by BEAM. Like operating system processes (but unlike operating system threads), they share no state with each other. The estimated minimal overhead for each is 300 words. Thus, many processes can be created without degrading performance. In 2005, a benchmark with 20 million processes was successfully performed with 64-bit Erlang on a machine with 16 GB random-access memory (RAM; total 800 bytes/process). Erlang has supported symmetric multiprocessing since release R11B of May 2006.

While threads need external library support in most languages, Erlang provides language-level features to create and manage processes with the goal of simplifying concurrent programming. Though all concurrency is explicit in Erlang, processes communicate using message passing instead of shared variables, which removes the need for explicit locks (a locking scheme is still used internally by the VM).

Inter-process communication works via a shared-nothing asynchronous message passing system: every process has a "mailbox", a queue of messages that have been sent by other processes and not yet consumed. A process uses the receive primitive to retrieve messages that match desired patterns. A message-handling routine tests messages in turn against each pattern, until one of them matches. When the message is consumed and removed from the mailbox the process resumes execution. A message may comprise any Erlang structure, including primitives (integers, floats, characters, atoms), tuples, lists, and functions.

The code example below shows the built-in support for distributed processes:

 % Create a process and invoke the function web:start_server(Port, MaxConnections)
 ServerProcess = spawn(web, start_server, ),
 % Create a remote process and invoke the function
 % web:start_server(Port, MaxConnections) on machine RemoteNode
 RemoteProcess = spawn(RemoteNode, web, start_server, ),
 % Send a message to ServerProcess (asynchronously). The message consists of a tuple
 % with the atom "pause" and the number "10".
 ServerProcess ! {pause, 10},
 % Receive messages sent to this process
 receive
         a_message -> do_something;
         {data, DataContent} -> handle(DataContent);
         {hello, Text} -> io:format("Got hello message: ~s", );
         {goodbye, Text} -> io:format("Got goodbye message: ~s", )
 end.

As the example shows, processes may be created on remote nodes, and communication with them is transparent in the sense that communication with remote processes works exactly as communication with local processes.

Concurrency supports the primary method of error-handling in Erlang. When a process crashes, it neatly exits and sends a message to the controlling process which can then take action, such as starting a new process that takes over the old process's task.

Implementation

The official reference implementation of Erlang uses BEAM. BEAM is included in the official distribution of Erlang, called Erlang/OTP. BEAM executes bytecode which is converted to threaded code at load time. It also includes a native code compiler on most platforms, developed by the High Performance Erlang Project (HiPE) at Uppsala University. Since October 2001 the HiPE system is fully integrated in Ericsson's Open Source Erlang/OTP system. It also supports interpreting, directly from source code via abstract syntax tree, via script as of R11B-5 release of Erlang.

Hot code loading and modules

Erlang supports language-level Dynamic Software Updating. To implement this, code is loaded and managed as "module" units; the module is a compilation unit. The system can keep two versions of a module in memory at the same time, and processes can concurrently run code from each. The versions are referred to as the "new" and the "old" version. A process will not move into the new version until it makes an external call to its module.

An example of the mechanism of hot code loading:

  %% A process whose only job is to keep a counter.
  %% First version
  -module(counter).
  -export().
  start() -> loop(0).
  loop(Sum) ->
    receive
       {increment, Count} ->
          loop(Sum+Count);
       {counter, Pid} ->
          Pid ! {counter, Sum},
          loop(Sum);
       code_switch ->
          ?MODULE:codeswitch(Sum)
          % Force the use of 'codeswitch/1' from the latest MODULE version
    end.
  codeswitch(Sum) -> loop(Sum).

For the second version, we add the possibility to reset the count to zero.

  %% Second version
  -module(counter).
  -export().
  start() -> loop(0).
  loop(Sum) ->
    receive
       {increment, Count} ->
          loop(Sum+Count);
       reset ->
          loop(0);
       {counter, Pid} ->
          Pid ! {counter, Sum},
          loop(Sum);
       code_switch ->
          ?MODULE:codeswitch(Sum)
    end.
  codeswitch(Sum) -> loop(Sum).

Only when receiving a message consisting of the atom code_switch will the loop execute an external call to codeswitch/1 (?MODULE is a preprocessor macro for the current module). If there is a new version of the counter module in memory, then its codeswitch/1 function will be called. The practice of having a specific entry-point into a new version allows the programmer to transform state to what is needed in the newer version. In the example, the state is kept as an integer.

In practice, systems are built up using design principles from the Open Telecom Platform, which leads to more code upgradable designs. Successful hot code loading is exacting. Code must be written with care to make use of Erlang's facilities.

Distribution

In 1998, Ericsson released Erlang as free and open-source software to ensure its independence from a single vendor and to increase awareness of the language. Erlang, together with libraries and the real-time distributed database Mnesia, forms the OTP collection of libraries. Ericsson and a few other companies support Erlang commercially.

Since the open source release, Erlang has been used by several firms worldwide, including Nortel and Deutsche Telekom. Although Erlang was designed to fill a niche and has remained an obscure language for most of its existence, its popularity is growing due to demand for concurrent services. Erlang has found some use in fielding massively multiplayer online role-playing game (MMORPG) servers.

See also

References

  1. "Release 27.2". 11 December 2024. Retrieved 17 December 2024.
  2. Conferences, N. D. C. (4 June 2014). "Joe Armstrong - Functional Programming the Long Road to Enlightenment: a Historical and Personal Narrative". Vimeo.
  3. "Clojure: Lisp meets Java, with a side of Erlang - O'Reilly Radar". radar.oreilly.com.
  4. "Influences - The Rust Reference". The Rust Reference. Retrieved 18 April 2023.
  5. "Erlang – Introduction". erlang.org.
  6. Armstrong, Joe; Däcker, Bjarne; Lindgren, Thomas; Millroth, Håkan. "Open-source Erlang – White Paper". Archived from the original on 25 October 2011. Retrieved 31 July 2011.
  7. Hitchhiker’s Tour of the BEAM – Robert Virding http://www.erlang-factory.com/upload/presentations/708/HitchhikersTouroftheBEAM.pdf
  8. ^ Armstrong, Joe (2007). History of Erlang. HOPL III: Proceedings of the third ACM SIGPLAN conference on History of programming languages. ISBN 978-1-59593-766-7.
  9. "How tech giants spread open source programming love - CIO.com". 8 January 2016. Archived from the original on 22 February 2019. Retrieved 5 September 2016.
  10. "Erlang/OTP Released as Open Source, 1998-12-08". Archived from the original on 9 October 1999.
  11. "Erlang, the mathematician?". February 1999.
  12. "Free Online Dictionary of Computing: Erlang".
  13. "History of Erlang". Erlang.org.
  14. Armstrong, Joe (August 1997). "The development of Erlang". Proceedings of the second ACM SIGPLAN international conference on Functional programming. Vol. 32. pp. 196–203. doi:10.1145/258948.258967. ISBN 0897919181. S2CID 6821037. {{cite book}}: |journal= ignored (help)
  15. Däcker, Bjarne (October 2000). Concurrent Functional Programming for Telecommunications: A Case Study of Technology Introduction (PDF) (Thesis). Royal Institute of Technology. p. 37.
  16. ^ "question about Erlang's future". 6 July 2010.
  17. "Concurrency Oriented Programming in Erlang" (PDF). 9 November 2002.
  18. Armstrong, Joe (20 November 2003). Making reliable distributed systems in the presence of software errors (DTech thesis). Stockholm, Sweden: The Royal Institute of Technology.
  19. McGreggor, Duncan (26 March 2013). Rackspace takes a look at the Erlang programming language for distributed computing (Video). Rackspace Studios, SFO. Archived from the original on 11 December 2021. Retrieved 24 April 2019.
  20. "Ericsson". Ericsson.com. 4 December 2014. Retrieved 7 April 2018.
  21. "Inside Erlang, The Rare Programming Language Behind WhatsApp's Success". fastcompany.com. 21 February 2014. Retrieved 12 November 2019.
  22. "Erlang/Elixir Syntax: A Crash Course". elixir-lang.github.com. Retrieved 10 October 2022.
  23. "Which companies are using Erlang, and why? #MyTopdogStatus". erlang-solutions.com. 11 September 2019. Retrieved 15 March 2020.
  24. "Which new companies are using Erlang and Elixir? #MyTopdogStatus". erlang-solutions.com. 2 March 2020. Retrieved 24 June 2020.
  25. "Erlang – List Comprehensions". erlang.org.
  26. "String and Character Literals". Retrieved 2 May 2015.
  27. "ect – Erlang Class Transformation – add object-oriented programming to Erlang – Google Project Hosting". Retrieved 2 May 2015.
  28. ^ Verraes, Mathias (9 December 2014). "Let It Crash". Mathias Verraes' Blog. Retrieved 10 February 2021.
  29. "Reactive Design Patterns —". www.reactivedesignpatterns.com. Retrieved 10 February 2021.
  30. Armstrong, Joe (September 2010). "Erlang". Communications of the ACM. 53 (9): 68–75. doi:10.1145/1810891.1810910. Erlang is conceptually similar to the occam programming language, though it recasts the ideas of CSP in a functional framework and uses asynchronous message passing.
  31. "Erlang Efficiency Guide – Processes". Archived from the original on 27 February 2015.
  32. Wiger, Ulf (14 November 2005). "Stress-testing erlang". comp.lang.functional.misc. Retrieved 25 August 2006.
  33. "Lock-free message queue". Archived from the original on 24 December 2013. Retrieved 23 December 2013.
  34. Armstrong, Joe. "Erlang robustness". Archived from the original on 23 April 2015. Retrieved 15 July 2010.
  35. "Erlang Supervision principles". Archived from the original on 6 February 2015. Retrieved 15 July 2010.
  36. "Erlang – Compilation and Code Loading". erlang.org. Retrieved 21 December 2017.
  37. "High Performance Erlang". Retrieved 26 March 2011.
  38. "Who uses Erlang for product development?". Frequently asked questions about Erlang. Retrieved 16 July 2007. The largest user of Erlang is (surprise!) Ericsson. Ericsson use it to write software used in telecommunications systems. Many dozens of projects have used it, a particularly large one is the extremely scalable AXD301 ATM switch. Other commercial users listed as part of the FAQ include: Nortel, Deutsche Flugsicherung (the German national air traffic control organisation), and T-Mobile.
  39. "Programming Erlang". Retrieved 13 December 2008. Virtually all language use shared state concurrency. This is very difficult and leads to terrible problems when you handle failure and scale up the system...Some pretty fast-moving startups in the financial world have latched onto Erlang; for example, the Swedish www.kreditor.se.
  40. "Erlang, the next Java". Archived from the original on 11 October 2007. Retrieved 8 October 2008. I do not believe that other languages can catch up with Erlang anytime soon. It will be easy for them to add language features to be like Erlang. It will take a long time for them to build such a high-quality VM and the mature libraries for concurrency and reliability. So, Erlang is poised for success. If you want to build a multicore application in the next few years, you should look at Erlang.
  41. Clarke, Gavin (5 February 2011). "Battlestar Galactica vets needed for online roleplay". Music and Media. The Reg. Retrieved 8 February 2011.

Further reading

External links

Programming languages
Categories: