# The development of Erlang

> An annotated edition of this paper on Fermat's Library, where scientists and readers explain its ideas, equations and history in the margins. Annotated edition: https://fermatslibrary.com/s/the-development-of-erlang

- **Authors:** Joe Armstrong
- **Published:** 1997
- **Topic:** Computer Science
- **Original:** https://s3-us-west-1.amazonaws.com/fermatslibrary/uploads%2F1622527118558-3y7tiaabeht-b5d13d4746e772858cb0e7fcf55a5549%2Fdevelopment_erlang.pdf
- **Pages:** 8
- **Annotations:** 23 comments in 21 threads
- **Featured:** Fermat's Library Journal Club
- **Annotated edition:** https://fermatslibrary.com/s/the-development-of-erlang

## Annotations

### Annotation 1 (page 1)

Beside the passage: “Joe Armstrong”

**Annotation** by Nilakantan Narasinganallur (2021-06-02):

> How do I download the paper for study and future use? Will I be violating any copyright issues? I will give credits while referring to the paper.

**Reply** by Grégoire Jadi (2021-06-03):

> See the notice below:
>
> > Permission to make digital/hard copy of part or all this work for
> personal or classroom use is granted without fee provided that
> copies are not made or distributed for profit or commercial advan-
> tage, the copyright notice, the title of the publication and its date
> appear, and notice is given that copying is by permission of ACM,
> Inc. To copy otherwise, to republish, to post on servers, or to redistribute to lists, requires prior specific permission and/or a fee.

**Reply** by Jemal Ahmed (2021-08-11):

> Amaizing work

### Annotation 2 (page 1)

Beside the passage: “Erlang is a concurrent programming language designed for programming large-scale distributed soft real-time control applications.”

**Annotation** by João Batalha (2021-06-01):

> ### Hard Real Time vs Soft Real Time
>
> A real time system is a system that must react to stimuli from the controlled object (or the operator) within time intervals dictated by its environment.  In other words, it's a system in which jobs / routines have a "deadline" that they have to finish by.
>
> You can subdivide real time systems into two categories:
> -  **Hard Real Time Systems:** The operation will be incorrect (with possible disastrous consequences) if it is not completed according to the designed time constraint.  e.g. Ballistic Missile, Air Traffic Control
> -  **Soft Real Time Systems:** The system's operation is degraded if a job is not completed within the specific time requirement. e.g. Computer Game, Telephone System

### Annotation 3 (page 1)

Beside the passage: “The design of Erlang was heavily influenced by ideas from the logic and functional programming communities. Other sources of inspiration came from languages such as Chill and Ada which are used in industry for programming control systems.”

**Annotation** by Grégoire Jadi (2021-06-03):

> CHILL is a procedural and object oriented programming language. Its design started in 1980 with the goal to become a standard to develop telecommunication systems.
>
> https://psc.informatik.uni-jena.de/languages/chill/chill.htm

### Annotation 4 (page 1)

Beside the passage: “Being a telecoms laboratory we were in the fortunate position of always having hardware to play with. The lab had a Ericsson MD110 (which is a smafl telephone exchange) which had been modified so it could be controlled by a conventional Unix machine. We programmed POTS1 in as many programming languages as we could lay …”

**Annotation** by João Batalha (2021-06-01):

> The Ericsson MD110 is a PBX system (Private Branch Exchange), which allows companies to run private telephone networks allowing users to communicate internally and externally.

### Annotation 5 (page 1)

Beside the passage: “The main conclusion [5] was that declarative language programs for POTS were a lot shorter and easier to understand than imperative language programs. Unfortunately the declarative languages lacked features for concurrency control and had poor error handling facilities.”

**Annotation** by João Batalha (2021-06-01):

> ### Declarative vs Imperative programming
>
> These are two programming paradigms that dictate how you express the intended behavior of your program. A good way to think about it is: Declarative programming is when you state what you want, whereas in Imperative programming you say how to get what you want.
>
> Generally, functional programming languages are considered declarative languages. Some languages support both imperative and declarative styles. Consider the following examples in Python:
> ```
> # Declarative - author does not specify implementation details
> small_nums = [x for x in range(20) if x < 10]
>
> # Imperative
> small_nums = []
> for i in range(20):
>     if i < 10:
>         small_nums.append(i)
> ```

### Annotation 6 (page 1)

Beside the passage: “1986 - 1989 The Prolog interpreter”

**Annotation** by João Batalha (2021-06-01):

> ### PROLOG
> PROLOG is a logic programming language (as opposed to an algorithmic language) conceived by Alain Colmerauer at the University of Aix-Marseille, France. The language was first implemented in 1973 and gained popularity in applications such as artificial intelligence and computational linguistics.
> Example PROLOG program:
> ```
> man(socrates).
> mortal(X) :- man(X).
> ```

### Annotation 7 (page 1)

Beside the passage: “Erlang was developed by the author and his colleagues at the Ericsson Computer Science Laboratory. Ericsson is currently the world’s largest supplier of telecoms systems and the world’s leading manufacturer of mobile phones.”

**Annotation** by João Batalha (2021-06-01):

> Even tho Ericsson's market share in the mobile phone market declined significantly since this paper was published, Ericsson is still one of the worlds largest suppliers of telecom equipment.
> ![](https://i.imgur.com/RTud8Ts.png)

### Annotation 8 (page 1)

Beside the passage: “Ericsson’s flagship product is a telephone exchange called the AXE lO which is programmed in a proprietary language called PLEX. A typicaf AXEl O system has over 5 million Iines of PLEX. The AXEIO is specified to have a “down time” of less than 3 minutes per year - such requirements are common in the telecoms industry.”

**Annotation** by João Batalha (2021-06-01):

> The AXE10 is part of the AXE telephone exchange product line of circuit switched digital telephone exchanges. The meaning of the designation AXE is not completely clear, but most sources agree that Automatic experimental Electronic switch is the most likely interpretation. The first AXE system was deployed in 1976. The  AXE10 system is still the most widely deployed switching system in the world.
> ![](https://i.imgur.com/utIzJ3c.jpg)
> *Ericsson AXE*

### Annotation 9 (page 1)

Beside the passage: “Ericsson’s flagship product is a telephone exchange called the AXE lO which is programmed in a proprietary language called PLEX. A typicaf AXEl O system has over 5 million Iines of PLEX. The AXEIO is specified to have a “down time” of less than 3 minutes per year - such requirements are common in the telecoms industry.”

**Annotation** by João Batalha (2021-06-01):

> PLEX (Programming Language for EXchanges) is a special-purpose, proprietary, real-time programming language. The language was developed by Göran Hemdahl at Ericsson in the 1970s.  PLEX has been described as "a cross between Fortran and a macro assembler".  It is an imperative language, with assignments, conditionals, goto’s, and a restricted iteration construct. It does lack some common statements from other programming languages such as while loops, negative numeric values and real numbers.

### Annotation 10 (page 1)

Beside the passage: “Having decided that we liked Prolog for programming POTS we started a series of experiments call LOTS (Lots of POTS) to program not only POTS but aleo an extremely large number of different telephony features in Prolog. Before long I had programmed a large subset of PABX features in Prolog. To do so I wrote a Prolog …”

**Annotation** by João Batalha (2021-06-01):

> PABX stands for *Private Automatic Branch Exchange* which is a technology which allows businesses to have a single access number to provide several lines to outside callers while providing a range of external lines to internal callers or staff. PABX performs all the switching necessary for making internal calls between extensions within the organizations.

### Annotation 11 (page 1)

Beside the passage: “Erlang grew out of a series of experiments which we performed to see if we could find better ways of programming telecoms systems. Our criterion for success was that we could program telecoms systems with less effort and fewer errors than could be done using conventional technology.”

**Annotation** by João Batalha (2021-06-01):

> It's important to underline that even tho Erlang is a language that is now used for a variety of applications its origins are very much connected to the need to solve a specific problem (as oppose to a more academic pursuit). As the author mentions, engineers at Ericsson were working on developing the next generation of telecom systems and were faced with a number of challenges:
> - massive scale
> - strict reliability requirements
> - complex systems (millions of lines of code)

### Annotation 12 (page 2)

Beside the passage: “During the period 1986-1988 members of the computer science lab worked closely with the Bollmora group, meeting once or twice a week. During this time the Prolog interpretor (and the language which it defined) changed rapidly, The language grew and evolved and somewhere along the line acquired a name, Erlang, named in …”

**Annotation** by João Batalha (2021-06-01):

> ### Agner Krarup Erlang
> Agner Erlang was a Danish mathematician, statistician and engineer, who pionnered the fields of traffic engineering and queueing theory. By studying a village telephone exchange he worked out a formula, now known as Erlang's formula, to calculate the fraction of callers attempting to call someone outside the village that must wait because all of the lines are in use.
> ![](https://i.imgur.com/z1OeIFZ.jpg)
> *A.K. Erlang*

### Annotation 13 (page 2)

Beside the passage: “The beam Performance has always been a major problem. In 1992 Bogumil Hausman started work on the BEAM.4 The BEAM compiles Erlang to C which can then be compiled with a conventional C compiler. The BEAM can afso compife to threaded code which can be freely intermixed with compiled code. Compiled code is faster but …”

**Annotation** by João Batalha (2021-06-01):

> BEAM is the virtual machine at the core of the Erlang Open Telecom Platform (OTP). BEAM (Bogdan's Erlang Abstract Machine) was effectively the successor to JAM (Joe's Abstract Machine). Today there are a number of languages that leverage BEAM:
> - Erlang
> - Elixir
> - LFE
> - Alpaca
> - Gleam

### Annotation 14 (page 2)

Beside the passage: “The jam machine By about 1988 is was clear that Erlang as it was now called wss a good language for prototyping telephone exchanges [10]. It was a strange mixture, with declarative features (inherited from Prolog), multi-tasking and concurrency (inherited from EriPascaJ and Ada) and an original combination of error …”

**Annotation** by Alex Castro (2021-08-12):

> Strand is a parallel programming language. The citation goes to a book but here is a link to a paper about Strand:
> https://www.osti.gov/servlets/purl/5395744

### Annotation 15 (page 2)

Beside the passage: “The jam machine By about 1988 is was clear that Erlang as it was now called wss a good language for prototyping telephone exchanges [10]. It was a strange mixture, with declarative features (inherited from Prolog), multi-tasking and concurrency (inherited from EriPascaJ and Ada) and an original combination of error …”

**Annotation** by João Batalha (2021-06-01):

> *JAM* stands for Joe's Abstract Machine

### Annotation 16 (page 2)

Beside the passage: “The jam machine By about 1988 is was clear that Erlang as it was now called wss a good language for prototyping telephone exchanges [10]. It was a strange mixture, with declarative features (inherited from Prolog), multi-tasking and concurrency (inherited from EriPascaJ and Ada) and an original combination of error …”

**Annotation** by Grégoire Jadi (2021-06-03):

> [Warren Abstract Machine (WAM)](https://en.wikipedia.org/wiki/Warren_Abstract_Machine) is an abstract machine for the execution of Prolog code.

### Annotation 17 (page 3)

Beside the passage: “. The tools”

**Annotation** by Stephen Cagle (2021-06-20):

> I wonder if this is still true? I would say that most software engineering is moving towards the amateur.

### Annotation 18 (page 3)

Beside the passage: “fat(N) when N > 0 -> N * fac(N-1) ; fat(O) -> 1.”

**Annotation** by João Batalha (2021-06-01):

> Further notes on the basic syntax of Erlang:
>
> ```
> -module(math).
> ```
> This is the file 'math.erl', the module and the filename must match
>
> ```
> -export([fac/1]).
> ```
> This exports the function 'fac' of arity 1 (1 parameter, no type, no name)
>
> ```
> fac(N) when N > 0 -> N * fac(N-1);
> ```
> If N > 0 recursively call the `fac` function, otherwise advance to next clause (the semicolon ; indicates `else`)
>
> ```
> fac(0) -> 1.
> ```
> If 0, then return 1 (period . means `endif`)

### Annotation 19 (page 3)

Beside the passage: “These include things like cross-compilers for interfacing Erlang to foreign language applications, an ASN. 1 interface compiler, an SNMP tool-kit, a HTTP-server etc. Many of the new users of Erlang are not initially attracted by the language but rather by the set of tools which comes with the language. For example, it …”

**Annotation** by João Batalha (2021-06-01):

> ### SNMP
> Simple Network Management Protocol (SNMP) is an application–layer protocol for exchanging management information between network devices. In other words it a network protocol to manage and monitor network elements. It is a part of Transmission Control Protocol⁄Internet Protocol (TCP/IP) protocol suite. It was formerly defined in [RFC1157](https://datatracker.ietf.org/doc/html/rfc1157)

### Annotation 20 (page 3)

Beside the passage: “append ([HIT], L) -> [Hlappend(T, L)]; append ([] , L) -> L.”

**Annotation** by Stephen Cagle (2021-06-20):

> I think it is interesting that [H|T] and {Key1, Val, S,B} (above) both rely on the fact that if they are not fully hydrated they do not pass. Means you can put the terminal condition at the bottom rather than being the first thing that needs be checked.

### Annotation 21 (page 6)

Beside the passage: “After he hads tarted work on the project he realised that he needed some money and some help. He got his money, and we got a type system,”

**Annotation** by João Batalha (2021-06-01):

> You can read more about the effort to create a type system for Erlang [here](https://homepages.inf.ed.ac.uk/wadler/papers/erlang/erlang.pdf). In the end, Erlang remains a dynamically typed language today.

## Full text

Extracted from the PDF. [Annotation N] marks where each annotation above sits.

#### Page 1

The development of Erlang

Joe Armstrong [Annotation 1]

Computer Science Laboratory

Ericsson Telecom AB

joeQcslab.ericsson.se

Abstract

This paper describes the development of the programming language Erlang during the period 1985-1997.

Erlang is a concurrent programming language designed for programming large-scale distributed soft real-time control applications. [Annotation 2]

The design of Erlang was heavily influenced by ideas from the logic and functional programming communities. Other [Annotation 3] sources of inspiration came from languages such as Chill and Ada which are used in industry for programming control systems.

1 Introduction

This paper describes the development of the Erlang programming language. Erlang is a language which draws heavily from various traditions in the logic, functional and realtime control programming communities.

Our goal was to make a language which could be used for building large soft real-time control systems. By large I mean systems with possibly millions of lines of code. By a soft real-time system I mean a system which does not faif catastrophically if a real-time deadline is missed.

Erlang was developed by the author and his colleagues at the Ericsson Computer Science Laboratory. Ericsson is currently the world’s largest supplier of telecoms systems and the world’s leading manufacturer of mobile phones. [Annotation 7]

Ericsson’s flagship product is a telephone exchange called the AXE lO which is programmed in a proprietary language [Annotation 8] called PLEX. A typicaf AXEl O system has over 5 million Iines of PLEX. The AXEIO is specified to have a “down [Annotation 9] time” of less than 3 minutes per year - such requirements are common in the telecoms industry.

The programming languages which are used for building such systems have to deal with a range of problems not usually encountered in traditional batch or interactive computer systems. For example, one requirement is that the system should be in “continuous” operation - this means we must do software upgrades without stopping the system. It also implies the use of fault-tolerant processors and a software architecture which protects the integrity of the system from various classes of programmer error,

Erlang grew out of a series of experiments which we performed to see if we could find better ways of programming [Annotation 11] telecoms systems. Our criterion for success was that we could program telecoms systems with less effort and fewer errors than could be done using conventional technology.

Permission to make digital/hard copy of part or all this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage, the copyright notice, the title of the publication and its date appear, and notice is given that copying is by permission of ACM, Inc. To copy otherwise, to republish, to post on servers, or to redistribute to lists, requires prior specific permission and/or a fee

This paper starts with a brief discussion of the various milestones which the language went through. This is followed by sections describhrg the language, finally future directions of research are mentioned.

2 Milestones

●

s

b

Early experiments

Being a telecoms laboratory we were in the fortunate position of always having hardware to play with. The [Annotation 4] lab had a Ericsson MD110 (which is a smafl telephone exchange) which had been modified so it could be controlled by a conventional Unix machine. We programmed POTS1 in as many programming languages as we could lay our hands on.

The main conclusion [5] was that declarative language programs for POTS were a lot shorter and easier to [Annotation 5] understand than imperative language programs. Unfortunately the declarative languages lacked features for concurrency control and had poor error handling facilities.

We concluded that we would like something like Pro log with added facilities for concurrency and improved error handling. No such language existed at the time.

1986 - 1989 The Prolog interpreter [Annotation 6]

Having decided that we liked Prolog for programming POTS we started a series of experiments call LOTS (Lots of POTS) to program not only POTS but aleo an extremely large number of different telephony features in Prolog. Before long I had programmed a large [Annotation 10] subset of PABX features in Prolog. To do so I wrote a Prolog meta-interpretor which added the notion of a process to Prolog and which added facilities for advanced error detection and recovery. This work is described in [1].

The Bollmora group

Using the results of the work with the Prolog interpreter we were able to attract the curiosity and interest of a group of engineers who were responsible for a future soft ware architecture of the Ericsson MD 110.

‘ POTS stands for Plain Old Telephony Service, that is, subscriber A calls subscriber B and they chat for a while

‘Who worked in Bollmora, Stockholm.

ICFP ’97 Amsterdam, ND 0 1997 ACM 0-89791 -918 -1/97 /0006 .,.$3.50

196

#### Page 2

●

●

This group thought that they could US( our results as a vehicle for investigate ing their own software architectures. This began a period of collaboration which led to the development of Erlang as a fully fledged language and to a new range of Ericsson products.

During the period 1986-1988 members of the computer science lab worked closely with the Bollmora group, meeting once or twice a week. During this time the Prolog interpretor (and the language which it defined) changed rapidly, The language grew and evolved and somewhere along the line acquired a name, Erlang, named in honor of the Danish mathematician Agner Krarup Erlang (1878- 1929) whose name is associated [Annotation 12] with the telecoms industry.

The jam machine By about 1988 is was clear that Erlang as it was now called wss a good language for prototyping telephone exchanges [10]. It was a strange mixture, with declarative features (inherited from Prolog), multi-tasking and concurrency (inherited from EriPascaJ and Ada) and an original combination of error handling mechanisms. Erlang was, however, tar too slow to be used for product development, The Bolhnora group did some measurements and decideil t}lat for product development they needed a system that was 40 times faster than the Prolog interpreter This requirement lead to the development of a number of different abstract lnachines and compilation techniques used for implementing Erlang. A cross compiler from Erlang to Strand [7] was developed. After a num- [Annotation 14] ber of experiments tht JAM [4] machine was invented. This was based on the Warren Abstract Machine with [Annotation 15] added primitives for concurrency and exception handling. [Annotation 16]

By this time the Erlang effort had grown to three people. Mike Wifliams wrote a byte code emulator for JAM code, I wrote the compiler and Robert Virding wrote the support libraries. While we only ever distributed one version of the system to externaf user:., internally there were severaf competing Erlang “engines” where we experimented with different implementation techniques. The resulting JAM implementation was delivered to the Bollmora group in 1989. Fortunately it was 70 times faster than the original Prolog interpretor - unfortunately they had now revised their original estimates and wanted a machine that was 280 times faster than the original.

Adding distribution

During the period 1989-1994 the Erlang “group” expanded (there has ne~,er been a formal group). Claes Vikstrom joined the group in 1990 and added distribution to the language. The original language had been designed with “hooks’ for adding distribution - but this was Iiever actually done until Claes implemented it. The Bollmora group had now decided to go ahead and build a new PABX in Erlang. Erlang wasn’t fast

●

9

●

enough but it was generally thought that the performance problems could be solved. In 1992 they started development of a product called the “Mobility Server”, In 199.5 this was launched and became part of the “Consono” product range. At the time of writing the Mobility Server is marketed in 12 countries. Among other things it is used to control the DECT mobile phone in the European Parliament in Strasbourg.

Fight for acceptance During the period 1992-1996 it was by no means clear that Erlang was suitable for programming large-scale industrial products. While we were very successful in a number of smalf projects, Erlang programming and programmers stilf represented a very small percentage of the programming effort at Ericsson. The Mobility server project continued and we attracted several new smalf projects. During this time we were involved in maasive “guerilla marketing” activities. I don’t think there was a single person in Ericsson who ever came out of Bjarne’s3 office without a copy of the Erlang manual under their arm!

The beam Performance has always been a major problem. In 1992 Bogumil Hausman started work on the BEAM.4 [Annotation 13] The BEAM compiles Erlang to C which can then be compiled with a conventional C compiler. The BEAM can afso compife to threaded code which can be freely intermixed with compiled code. Compiled code is faster but takes up more space than threaded code. In a large embedded system with millions of lines of code, the volume of object code can be a major problem, Infrequently used and non-performance critical parts of the system can be compiled to threaded code while performance critical parts of the system can be compiled to native code. There are performance tools which we can use to analyse the system and find out which parts of the system need to be native code compiled. The BEAM is described in [6]. In many applications the BEAM is comparable with C in performance terms. The BEAM replaced the JAM as the principle system for new product development in 1997.

Erlang Systems Up to 1995 most users were “enthusiasts” and Erlang spread internally within Ericsson by “word of mouth”. We didn’t find new users, they found us.

As the language spread we needed to produce training material and hold courses to train new users. Initially, all courses were held at the Computer Science Lab by members of the Erlang “group”. Whife holding such courses was great fun, demand soon far outstripped supply. In April 1993 a new company “Erlang Systems” was formed to handle sales, marketing, education and consulting of Erlang. We had been in the fortunate position of having supervised a number of Master degree

3 Boss of the computer science lab. 4 Bogdans’s Erlang Abstract machine.

197

#### Page 3

students in conlputer science at the [Jlliversity 0[ tlppsala. Having conlpleted i]. Masters degree many of these students were employed by Erlang Systems. Mike Williams moved from the Computer Science Laboratory to manage Erlang Systems and had soon built up a strong team of consultants and impressive training facilities. In 1996 over 500 Ericsson programmers attended courses at Erlang Systems. Erlang consulting is one of the most important factors that have led to the spread of Erlang within Ericsson. In the first Erlang projects there ww very close contact between the developers and the users. We knew every user and could provide individual help and tuition - this doesn’t scale. Now, when we start a new project, we aJways try to get at least two Erlang Systems consultants working on the project. They provide a vital link between the users and developers of Erlang. This is a significant factor in the success of new projects. It is also interesting to note that the skll level required for an entry-level industrial programmer has increased in recent years. A good degree in computer science is now a pre-condition for working with state of the art software technology. The days of the amateur hacker are fast disappearing.

. The tools [Annotation 17]

The current Erlang system comes with an extensive toolkit. As well as the obvious software tools (yacc, lex look-a-likes etc. ) there is a wide range of tools which are useful for building telecoms applications.

These include things like cross-compilers for interfacing Erlang to foreign language applications, an ASN. 1 interface compiler, an SNMP tool-kit, a HTTP-server etc. Many of the new users of Erlang are not initially attracted by the language but rather by the set of tools which comes with the language. For example, it is extremely easy to Imihi an SNMP application using the Erlang SNMP toolkit. The SNMP toolkit, for ex- [Annotation 19] ample, contains a MIB compiler, and set of default methods which allows a non-expert user to build an SNMP agent in a matter of hours. Doing this in a conventional language is much more difficult. Many of the first versions of the tools were written by students = part of their Maater thesis work.

● Mnesia

Many real-time applications need access to data over long periods of time. For example, in a telephone exchange subscriber data must be stored for many years and must be accessible within a few milliseconds, Charging data (telephone bills) must be kept and never lost.

Mnesia [9] is a real-time distributed database designed for programming telecoms applications in Erlang. Amnesia is written entirely in Erlang.

● OTP

On 1 January 1996 a new Ericsson division was created to support applications written in Erlang. Our users want a lot more than just a programming language.

For example, some users want not only the language but also the operating systems and the hardware platform to be delivered in one package. The OTP (Open Telecom Platform) division can provide Ericsson users with anything from a simple Erlang system which runs on a PC to an embedded system complete with hardware. The division has the goal of providing prospective users with a turn-key system which they can turn on and start programming from day one of a project. Standard OTP software comes with extensive libraries which solve common application problems.

Another goal of the OTP division w= to transfer r~ sponsibility for the maintenance and support of the Erlang system from the Computer Science Laboratory to a mainstream Ericsson division.

3 Erlang in 14 Examples

The previous sections described the development of Erlang. The following sections describe Erlang through a number of small examples.

3.1 Sequential Erlang

Example 1- Factorial

All functions are defined in modules, for example, factorial can be written:

-module (math) . -export ([f ac/11 ) .

fat(N) when N > 0 -> N * fac(N-1) ; [Annotation 18] fat(O) -> 1.

The annotation -export ([f ac/ 11 ) means the function f ac with one argument is from the module. Only exported functions can be called from outside the module.

Once a module has been loaded into the system the query evaluator can be used for function evacuation:

\> math: fac(25) . 15511210043330985984000000

Example 2- Binary Tree

lookup (Key, {Key, Val, -, _}) ->

{ok, Vail; lookup (Key, {Keyl ,Val ,S ,B}) when Key<Keyl ->

lookup (Key, S) ; lookup (Key, {Keyl ,Val, S, B}) -> lookup (Key, B) ; lookup (Key, nil) ->

not-f ound.

Here the tuple {Key, Val, S ,B} represents a node of a binary tree. Tuples store fixed numbers of arguments.

Example 3- Append

append ([HIT], L) -> [Hlappend(T, L)]; [Annotation 20] append ([] , L) -> L.

198

#### Page 4

The notation [HI T] when occurring in ii function head denotes a pattern matching operation on a list. His the first element of the list, T is the remainder of the list. When occurring on the right hand side of a production it denotes a list constructor.

Example 4- Sort

sort ( [pivot ITI ) ->

sort([Xll X <- T, X < Pivot]) ++ [Pivot] ++ sort([Xll X <- T, X >= Pivot]); sort([l) -> [1.

The notation [Expr II . ..1 introduces a list comprehension and ++is the infix append operator.

Examples- Adder

Lambda expressions are introduced with the syntax:

fun{. . . ) -> end

As an example we can write:

\> Adder = fun(N) -> fun(X) -> X + N end end. SFr.m > G = Adder (lO). #Fun > G(5). 15

3.2 Concurrent Erlang

Example 6- An area Server

Starto ->

spam(funo -> loop(O) end).

loop(Tot) ->

receive

{Pid, {square, Xl} -> Pid ! X*X, loop(Tot + X*X); {Pid, {rectangle, [X,yI}}->

Pid ! X*Y, loop(Tot + X*Y); {Pid, areas} ->

Pid ! Tot, loop(Tot) end.

This creates an “area server” - you can ask the server what the area of a square or rectangle is, or, you can ask it to return the total of all areas that it has been requested to compute.

In the above, spawn(Fun) creates a parallel process which evaluates the lambda expression Fun. Spawn returns a process identifier (Pid) which can be used to communicate with the process.

Here Pid ! M sends the message M to the process Pid. receive . . . endis a pattern matching operation which receives a message, Send is an asynchronous non-blocking operation.

Example 7- An area client

Client code which uses the above server can be written:

Pid ! {selfo, {square, 10}}, receive

Area ->

. . . end

Example 8- Global Server

In the above examples, the process identifier of the server hadtomade known tothe client. Toprovide a global service we can associate a process identifier with a global name se follows:

. . . Pid - spavn(Fun), register(area-server, Pid), . . . area-server ! . . .

This associates the global name area-server with Pid. Thereafter any process evaluating in the node where this name was registered can send a message to the process with the syntax area-server ! ?lsg

3.3 Distribution

Example 9- Spawning ona remote node

Spawn can be used tocreate aprocess ofa different Erlang node.

. . . Pid = sparm(Fun@Node) . . . alive (Node) . . . not-al ive(llode)

The primitives alive and not-alive signify a node’s willingness to participate in distributed computations. If they have not evaluated alive they remain “anonymous” and cannot take part in distributed computations.

3.4 Error detection

Erlang is designed for programming “robust” systems, so there are a number of primitives for trapping errors. Error recovery is not automatic. The programmer must design a fault-tolerant architecture which can be implemented using the error detection mechanisms.

Example 10- Catch

\> x = 1/0. ** exited: {badarith, divide_by_zero} ** > X = (catch 1/0). {’EXIT’, {badmith, divide-by-zero}] > bo. X = {’EXIT’,{badarith, divide-by_zero}}

catch (Expr) converts any error occurring within Expr into a term describing the error.

199

#### Page 5

Example 11- Catch and throw

case catch f(X) of

{exception, Why} ->

Actions; NormalReturn ->

Actions; end,

f(x) ->

. . . Nomal.retumt-value; f(x) ->

. . . throw({exceptionl, . ..}).

Non-local returns can be performed with throv(Expr). Expr is evaluated and becomes the value of the enclosing catch,

Example 12- Links and trapping exits

Processes can be linked together. If a process dies an message is sent to all processes to which it is linked.

process-flag(trap-exits, true), P = spavn-link(Node, Fun), receive

{’EXITJ, P, why} -> Actions; . . . end

error

spaun.link(Fw) creates a parallel process which evaluates Fun and creates a link between the process which performs the spawn (the parent) and thenewly created process (the child).

If an exception is raised in the child process then an error message is sent to all processes which the child process is linked to. In our example an error in the child process will cause an error message to be sent to the parent process. The parent process can receive the error message and take appropriate action.

Example 13- Undefined processes

Ifwecallllod:Func (Argl,. .Argn) and this function cannot be located in the system, then Hod: Func behaves as if it had been defined as follows:

Hod:Func(Argl, . . . . Argn) -> error_handler:undefined-functlon(Hod, Func, [Argl, . . Argnl)

The function undefined_function can be definedby the user or the system default can be used. It is usually defined something like:

undefined-function(Hod, Func, Args) ->

case code: ensure_loaded(Hod) of

{module, Hodl ->

case is-exported(Hod, Func, length(Args)) of true ->

apply(Hod, Func, Args); false ->

exit({undef, {Hod,Func,Args}})

end; {module, Other} ->

exit({undef, {Hod,Func,Args}} ); {interpret, Hod} ->

int:eval(Hod, Func, Args); Other ->

exit({undef,{Hod,Func ,Args}}) end.

3.5 Hot code replacement

Example 14- Code replacement

Erlang is designed for “non-stop” systems. We need to be able to replace code and data without stopping the system. This example shows how we can change codein a server, without stopping the server.

loop(Data, F) ->

receive

{request, Pid, (?1 ->

{Reply, Datal} = F(Q, Data), Pid ! Reply, loop(Datal, F); {cha.nge_code, Fl} ->

loop(Data, Fl) end

The above code represents a server. Data represent the local state of the server. F is a lambda expression which determines the behaviour of the server. Tochange the code in the server we send it the message {change_code, Fl} The garbage collector willremove the old function.

4 Higher Order Processes

Most large Erlang systems are programmed by re-using code from a number of programming patterns which we call behaviors. This is a processes whose behaviour will be determined by a lambda expression at run-time.

As an example of a behaviour we show how a simple client-server model can be programmed. Firstly the code for the generic part of the client-server:

Generic Client Server

-rnodule(cs).

-export([start/3, rpc/2, loop/21).

start(?iae, Data, Fun) ->

register(Name,

spavn(funo ->

loop(Data, Fun) end) ) .

rpc(llime, q) ->

Tag = refo, IJame ! {query, selfo, Tag, receive

{Tag, Reply] -> Reply end.

loop(Data, Fun) ->

u}*

200

#### Page 6

receive

{query, Pid, Tag, Q} ->

{Reply, Datal} = Fun(Q, Data), Pid ! {Tag, Reply}, loop(Datal, Fun) end.

The above code provides skeleton code for a client-server. We can parameterise it by instantiating the variable Fun with a lambda expression which gives the server its desired behaviour.

Forexarnple, aKey-Value dictionary server can be made as follows:

A key-Value Server

-rnodule(kv) .

starto -> cs:start(keydb, [],

add(Key, Val) -> cs:rpc(keydb, lookup(Key) -> cs:rpc(keydb,

handler({add, Key, Val}, Data) {ok, add(Key,Val,Data)]; handler({lookup, Key}, Data)

{find(Key, Data), L)ata}.

add(Key,Val, [{Key,_}lT]) ->

[{Key,Val}lT]; add(Key,Val, [HIT]) ->

[Hladd(Key,Val,T}I ; add(Key,Val, Kl) ->

[{Key,Val}].

find(Key, [{Key,Val}l_]l ->

{found, Vail; find(Key, [HIT]) ->

find(Key, T); find(Key,D) ->

error.

fun handler/2).

{add,Key,Val}). {lookup,Key}).

->

->

Insequential programnring a small number of higher order functions (map, fold, zip etc.) provide a library of functions which the programmer can re-use in a number of different contexts. Note thereis alirnit edsetofsu chfunctions. Toomany ortoo abstract functions would not help.

In concurrent programming we have found that most concurrent programs can be built from a small number of higher order processes (such as the client-server) example. In a given application between 5 and 10 such higher-order processes seems to capture 95 ‘%oof the concurrency mechanisms.

Interestingly the generic part of the higher-order process is often not well-typed, but the functions which parameterise the process are.

5 Enter The Type System

Erlang has a dynamic type system which was inherited from Prolog, All types are checked at run-time. Nonsense expressions (for example I + true) are not type-checked at compile time but result in run-time exceptions.

In 1995 Phil Wadler decided that Erlang needed atype system, and promptly informed us that he was makkrg one.

After he hads tarted work on the project he realised that he [Annotation 21] needed some money and some help. He got his money, and we got a type system,

At the time of writing a Haskell prototype of the type checker [8] is being evaluated and the type checker itself is being re-writtenin Erlang.

We areevahrating the type systemby type checking all the libraries in the standard Erlang distribution. This work is not complete, but we can make certain observations about the type system.

The first point to note is that the type checker is totafly free-standing from the Erlang system itself. Nochanges have been made to Erlang to accommodate the type system.

A consequence of this is that theuser is free to compile and run programs which the type checker says are not welltyped. This is in contrast to say Haskell, or ML where a type-incorrect program cannot be compiled or run.

Many programs behave correctly despite the fact they are not well-typed. This is especially true of “systems software” -for example, theprograrnsin thekernel of the Erlang run-time which are responsible for IO and distribution perform highly complex generic operations on arbitrary data structures.

In the Erlang type system ausercan declare a type. For example:

-type fac(into) -> into.

fat(N) vhenN > 0 -> N * fac(ll-l); fat(O) -> 1.

Ifa typeis supplied it is checked by the type checker. Types can be annotated unchecked. This means that the type checker accepts the supplied type without analyzing the function tosee ifit hasthetype the programmer intended.

In practise this turns out to be very useful for forcing bizarre code through the type checker. An example is the code for the Erlang “pretty printer” The pretty printer contains code like:

-unchecked([pp/1] ). -type pp(l) -> deepstringo.

pp(X) then tuple(X) ->

pp_list(tuple_to_list(T) ); pp(X) when list(X) ->

. . . pp(X) when float(X) ->

. . .

ppis a function which turns any arbitrary data structure into a deep list of characters. We tell the system that pp is of type l->deepstringo where 1 is the universal type.

This is a correct statement about the program but one which cannot be inferred by the type checker.

In type checking the standard libraries we have found the following:

● The type system has uncovered no errors. The kernel

libraries were written by Erlang “experts” - it seems that good programmers don’t make type errors. It will be interesting to see if this remains true when we start type checking code written by less experienced programmers.

201

#### Page 7

●

●

s

Certain libraries (ordsets, diet etc. ) passed the type checker at the first attempt. The derived types corresponded in most c~ses to our intuition of what the derived types shouhl be. Adding type declarations (mostly for documel,tatioll purpose) was a trivial operation. Interestingly we could often remove a number of comments and replace them by more precise type declarations. Thus in diet.erl we replaced comments like:

~~ fetch(Key, Diet) -> Value XX find(Key, llict) -> {Olr,valuel I error ~~ store(Key, Value, Diet) -> Diet’

With type declaration:

-deftype dict(Key, Val) = [{Key, Val}].

-type fetch(Key, dlct(Key, Val)) ->

Val. -type find(Key, dlct(Key, Val)) ->

ok{Val} I error. -type store(Key, Val, dict(Key, Val)) -> dict(Key, Val).

Which says the same thing only more precisely.

Many modules did not type check at the first attempt. We had to re-write some functions or add unchecked annotation to force the code through the type checker. In complexmorlules about 10% ofthefunctions needed small changes. In t}le vast majority of cases a small change to the function corrected the type error. In a minority ofcases we had to resort to adding unchecked annotations. Even iu the kernel system modules we were able to provide readable types for the majority of functions and not resort to the unchecked annotation. uncheckedordy had to be used when the Erlang functions contained primitives such as apply etc. which could not be analysed by the type checker.

Debugging (i.e. fincling the source) of the type error was i;-sorne’ cases extr&lely difficult. This proved to be very frustrating. Well-tested programs which we believed to be correct were rejected by the type checker - finding exactly what was wrong was sometimes very difficult.

6 The future

Where is the research leading us?

● Very large systems

How can we build very large systems? The problems associated wit h building very large systems seem to have more to do with software architectures than choice of programming language. We have found that the use of program patterns (or higher order processes) greatly helps users structure large software systems. It has often been speculated that the advantages of a strong type system will be seen in very large software systems. We intend to test this hypothesis.

●

●

Evolving systems As systems evolve and as we learn more we discover better ways of programming things. Early design decisions turn out to be wrong. We often wish to change some of tbe major system interfaces which turned out to be wrong,

Project managers worry about “backwards compatibility” and are very reluctant to accept changes to the standard system software. Any change to the basic system invalidates their test procedures and can delay introduction of a new product. While in the shortterm is is desirable to keep the system as stable se possible, in the long-term we must allow systems to evolve and phase out old code and design decisions.

We are interested in techniques (for example, partial evahration) that can simplify (orin the best case automate) the transition from an older to a newer version of the system.

Performance Certain applications cannot be efficiently programmed in Erlang. We are considering adding imperative features to the language to solve these problems,

7 Reflections

Erlanghas spread successfully from the laboratory toanumber of commercial products. We can speculate se to the reasons why this has occurred. Some of the more important factors seem to be:

●

●

●

●

●

real problems We work on real problems. We tend to make progress when we cannot solve a particular problem with the existing technology. Progress has often come when a user came with a problem which could not be solved in Erlang.

working within the organisation

We work within the Ericsson organisation. It is far easier to “sell” an idea internally than to come to the organisation from outside.

organisational support

There is a gap between the best that a laboratory with limited resources can produce and what is minimally acceptable for a commercial product. Ericsson has provided financial support and created new jobs as necessary to help fill this gap.

we can provide good support

Good documentation, courses, e-mail, hot-line telephone support etc. are essential in psasing from the “enthusiast” to the “main-stream” phase of development.

lots of tools Project managers are not interested in programming languages. They arenotinterested informal anything and don’t give a hoot about types or calculi.

They are however, interested in short “time to market” and in writing bug-free software. The provision

202

#### Page 8

of large numbers of software tools can greatly reduce software development times and improve the quality of the software. These tools are specific to our problem domain. Thus we have tools for making SNMP MIBs, for nlanipulating ASN. 1 data ty])es, for building fault-tolerant duplicated data-bases with hot-standby etc.

● Foreign language interfaces

Typicaf systems are written in severaf different languages. Erlang is not good at everything. Large parts of a system might use purchased software packages written in C. Efficient integration with C is essential

References

[1] .J. L. Armstrong, S. R. Virding and M. C. Williams. Use

of Prolog for developing a new programming language. The Practical Application of Prolog London l-3 Aprif 1992

[2] J. L. Armstrong, M. C. Williams, C. Wikstromand S.

R. Virding. Concurrent Programming in Erlang, 2nd ed. Prentice Hall (1995)

[3] J. L. Armstrong. Erlang- Asurvey of thelanguage and

its industrial applications. In Proceedings of tire symposium on industrial app./ications of Prolog (HVAP96). 16 – 18 October 1996. Hino, Tokyo Japan.

[4] J. L. Armstrong, B. Dicker, S. R. Virding, and M.

C. Williams, Implementing a functional language for highly paralfe] reaJ timeapplications. 8th Int Conf. on Software Engineering for Telecommunication Switching Systems, Florence 30 March-1 April 1992.

[s] B. Dicker, N. Elahiewy, P. Hedeland, C. W. Welin C.

W. and M. C. Williams. Experiments with Programming Languages and Techniques for Telecommunication Applications. SixtJ~ International Conference on Software Engineering for Telecommunication Switching Systems. Eindhoven, 1986.

[6] B. Hausman. Turbo Erlang: Approaching thespeedof

C.In Implementations of Logic Programming Systems, pp. 119-135, ed. Evan Tick and Giancarlo Succi, Kluwer Academic Publishers (1994).

[7] I. Foster and S. Taylor. STRAND: New Conceptsin

ParaUel Processing. Prentice Hall, 1989.

[8] S. Marlow, and P. Wadler. Apractical snbtyping sys-

tem for Erlang. In ACM International Conference on Functional Programming, 1997.

[9] C. Wikstrom and H. Nilsson. Mnesia - An Industrial

DBMS with Transactions, Distribution and a Logicaf Query Language. International Symposium on Coop erative Databme S,ystems for Advanced Applications. Kyoto Japan 1996

[10] K. Odling. New technology for prototyping new ser-

vices. In Ericsson Review No. 21993.

203

---

Source: [Fermat's Library](https://fermatslibrary.com/) — https://fermatslibrary.com/s/the-development-of-erlang. More annotated papers: https://fermatslibrary.com/llms.txt
