# Erlang Programming/Printable version

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Erlang_Programming

# History

The Erlang language was first written in Prolog by Joe Armstrong. Joe is a known fan of Prolog and borrowed much syntax from Prolog in the design of Erlang. This first Prolog version of Erlang was slow and motivated the creation of a virtual machine. Later an emulator called the BEAM (Bogdan's Erlang Abstract Machine) was written in C and is about 200,000 lines of code. It is thought that Erlang is both a reference to mathematician Agner Krarup Erlang and short for "Ericsson Language", due to its place of birth.

## References

* ↑ Audio interview with Joe Armstrong from (http://www.se-radio.net)
* ↑ Mailing list discussion, 1999 (https://erlang.org/pipermail/erlang-questions/1999-February/000098.html)

# Overview
## Everything is a process

Software technologies often use a particular organizing principle. In Linux, everything is a file. In Ruby, everything is an object. In lisp, everything (program or data) is a list. In Erlang, the most important unit of organization is the process. Each process has an ID and at least one function that starts it (an entry point). In theory, there could be multiple entry point functions for a process. Each process is not limited to one function when running. On the contrary, one can have a whole barrel-of-functions that recursively call one-another and behave together as one process. GS based graphics programs in Erlang often use the barrel-of-functions per process technique to handle GUI events. CPU time is scheduled in a round robin fashion with equal time slices to each process.

## Messages

Processes send messages and receive messages from one another. Messages are read with pattern matching. The messages are matched in a fifo (first in, first out) way.

## Be parallel safe

To be serial-safe we need to control side effects. As a solution, first we invented structured programming, then object oriented programming. Each time the goal was to isolate state and variables to reduce side-effects. In the same tradition, side effects are more restricted in Erlang. If a function has no state then it will behave the same way every time. If a function has no side effects, then it cannot cause other functions to break.
   A pure function is a function that returns the same value given the same arguments regardless of the context of the call of the function. This is what we normally expect from a mathematical function. A function that is not pure is said to have side effects.
   Side effects typically occur if a function a) sends a message b) receives a message c) calls exit d) calls any BIF* which changes a processes environment or mode of operation (e.g. get/1, put/2, erase/1, process_flag/2 etc).
—quoted from Erlang Programming Rules (see references)
* Note: "BIF" stands for "built in function"

## Forget state

In general, state is forgotten in Erlang functions. Iteration is simulated by recursion. Variables can only be assigned once during each function call. State is carried by function arguments or state is put into a database if absolutely necessary. Avoiding state protects the integrity of processing in parallel. Each function call can be thought of as the creation of a pocket universe that has a set of equations that are true for the extent of invocation. Alternatively, one could conceive of erlang as a system to program with a kind of temporal logic. Some say that Erlang does not even have variable assignment, it only has pattern matching.
Head must always match in a consistent way or the containing process will fail.
Pattern matching can be thought of as a series of assertions that must be true.

## Mixing paradigms

Simple object oriented programming can be simulated with erlang by using processes for objects and messages for methods.

## The new software crisis

In 2003 Moore's law took a sharp turn. Overheating caused microprocessors to limit their speed to 4 GHz. The solution was to create multicore processors. This allowed Moore's law to continue but only in a parallel way. Multicell computing created a new software crisis, the MIMD (Multiple Instruction Multiple Data) software crisis. SIMD (Single Instruction Multiple Data) is relatively easy, MIMD is difficult. (Ref:The free lunch is over). MIMD programs are needed to make use of the new multi-core computers, otherwise, Moore's law breaks.

## Uses of Erlang

Erlang is well suited to address the new MIMD software crisis. Erlang can be used for agent programming because of parallel processes and message passing. Erlang can be used for classical AI programming because it is a symbolic language. Because of extreme process isolation it should work well for genetic/evolutionary programming.

## References

- The free lunch is over, Dr Dobbs Journal, March 2005. (html)
- Rules of Erlang programming from erlang.se (html)
- Joe Armstrong (2003). "Making reliable distributed systems in the presence of software errors". Ph.D. Dissertation. (pdf)

# Getting Started

← Overview | Terms →

## Getting Erlang

Erlang/OTP is available as free software from Open Source Erlang Downloads. Once you have downloaded the Erlang/OTP distribution, you will need to compile it (if on a Unix platform) and install it.

## Installing Erlang

In addition to the brief instructions below, you may wish to consult the Installation Guide.

### Unix

Unpack the source distribution. Decide where you want Erlang and its libraries installed. For our example, we will assume you want it in /usr/local/erlang/otp_r11b. Create this directory, as well as a build directory for building the Erlang sources.
From within the top-level directory, type ./Install /usr/local/erlang/otp_r11b. This will configure, build and install the Erlang/OTP distribution.
Add the distribution's bin directory to your path. You may wish to set this in your shell initialization file.

### Microsoft Windows

The distribution is a self-installing .exe file. Invoke it (for example, by double-clicking on its icon) and answer the prompts.

## The Erlang Shell

Erlang comes with a shell which is used interactively when controlling the Erlang environment and developing programs. On Unix, invoke the shell by typing erl on the command line. On Windows, type werl on the command line, or double-click the Erlang shortcut icon.
This starts the Erlang system and provides a shell for input and evaluation of Erlang.

## Your First Erlang Code

At the shell prompt, type "hello, world!" followed by a dot (.). You can follow that up with some arithmetic. Or answer the question "What is six times 9?" in base-13 notation:
When you are ready to exit, you can stop the Erlang system using the halt built-in function:

# Quick tips

One thing that can slow you down when you are getting started or trying to do some rapid prototyping is to export functions all the time. Rather, you can use the compiler directive. This makes programming erlang much more enjoyable, not to have to manually type:
everytime you add a function and would like to test it. Rather, you can use:
You can manually export only the things you need to when you are done with the program.
Another handy trick is to use
Rather than compile the latest version all the time.
or is it
?Module in code gives the current module name, which is super helpful when spawning.
Otherwise, you need to change the module name in every spawn every time you change the name of the module. If you would like to keep an eye on a process you can monitor it, after you have registered it.
A helpful utility function is rpc.
This helps keep synchronous commands between processes from getting answers from the wrong process. We force the identification of the process providing the answer, and sequential queuing should handle the rest.

# Terms

← Getting Started | Pattern Matching →
The basic unit of expressing a value in Erlang is the term. Terms are comprised of one of Erlang's simple or complex types.

## Integers

Integer constants are written as numbers, optionally prefixed with a base and the octothorpe (#):
Erlang uses arbitrary-precision integers, which support integers with any number of digits.
Erlang also provides another syntactic shortcut: you can write an integer as the dollar sign ($) and a character, and the value is the ASCII value of that character. This is of use when handling strings, as strings are typically represented in Erlang as lists of integers (see Strings, below).

## Floats

Floats (floating-point numbers) are written as numbers with decimal places, optionally with an exponent separated from the number with the letter e.

## Atoms

Atoms are named constants. Atoms begin with a lower-case letter and can contain letters, digits and the underscore character (_); or they are quoted with single quotes (').
The special atoms true and false represent boolean values.
Atoms are often used as the keys in key-value pairs, indicators of success and failure (e.g. ok and error) and to identify parts of a complicated structure for Pattern Matching.

## Tuples

Tuples are terms composed of multiple values, and are of fixed length. Tuples are surrounded by braces ({ and }), and the elements of the tuple (any Erlang term, including tuples) are separated by commas.
The 3rd example shows something called a tagged tuple. Where possible use tagged tuples as they make it clear what the tuple is supposed to represent. Later on we will look at records which is just a shorthand for tagged tuples.

## Lists

Lists are terms composed of multiple values, of varying length. Lists are surrounded by brackets ([ and ]) and each member of the list (any Erlang term, including lists) separated with commas.
Lists can also be composed of a head and tail portion, separated by the vertical bar character (|): [Head|Tail]. The Tail can be any valid Erlang term, but is usually a list representing the members of the list after the head.
Lists in which the smallest possible tail is the empty list () are known as well-formed lists.

### Strings

Erlang has no separate string type. Strings are usually represented by lists of integers (and the string module of the standard library manipulates such lists). Each integer represents the ASCII (or other character set encoding) value of the character in the string. For convenience, a string of characters enclosed in double quotes (") is equivalent to a list of the numerical values of those characters.
The Erlang shell "guesses" whether a given list is a printable string and prints it that way for convenience.

## Pids

A Pid or process id is a special type in Erlang. To see what one looks like you can get the pid of yourself with self.

## Refs

A ref (or reference) is a term which is unique, even across Erlang nodes. You can create a new ref by calling erlang:make_ref. A reference is only used as a unique tag or identifier. An Erlang reference should not be confused with a reference in C/C++.

## Other types

Erlang has other types, such as funs (closures), bit-strings, binaries (continuous blocks of arbitrary data) and ports (port identifiers), that will be covered in their appropriate sections.

# Pattern Matching

← Terms | Expressions →
Erlang uses powerful pattern-matching to bind variables to values. Pattern matching can be explicit, as when the = (pattern matching operator) is used, or implicit, as when a function call is processed and a function's actual arguments are matched with its formal parameters.

## Patterns

Patterns look the same as terms - they can be simple literals like atoms and numbers, compound like tuples and lists, or a mixture of both. They can also contain variables, which are alphanumeric strings that begin with a capital letter or underscore. A special "anonymous variable", _ (the underscore) is used when you don't care about the value to be matched, and won't be using it.
A pattern matches if it has the same "shape" as the term being matched, and atoms encountered are the same. For example, the following matches succeed:
* A = 1.
* 1 = 1.
* {ok, A} = {ok, 42}.
* [H|T] = [1, 2, 3].
Note that in the fourth example, the pipe (|) signifying the head and tail of the list as described in Terms.
These matches fail:
* 1 = 2.
* {ok, A} = {failure, "Don't know the question"}.
* [H|T] =.
In the case of the pattern-matching operator, a failure generates an error and the process exits. How this can be trapped and handled is covered in Errors.
Patterns are used to select which clause of a function will be executed (this is covered in Functions; which option to select in a case expression (Expressions); and which messages to retrieve from the mailbox (Processes).

### Variables

Erlang variables are single-assignment variables that do not have to be declared. They are written with a capital letter or underscore followed by an alphanumeric sequence. They are bound to values using the pattern matching mechanism. The Erlang compiler will produce an error if an unbound variable is used, and a warning if a bound variable is not used. Sometimes you might encounter a _Var variable. This variable is bound and does contain a value, however it suppresses compiler warnings regarding unused bound variables.

## Notes

* ↑ Since Erlang variables are immutable, consider examples like this to be standalone--even though the A is used twice, it's a different A each time!

# Expressions

← Pattern Matching | Functions →

## Expressions

Erlang statements look a little like sentences. One statement is a series of comma separated expressions ending with a period. Erlang expressions can either be ignored, stored, or returned depending on their position and structure in a statement.
In this Erlang example the expression: 4+3 is computed, the expression H=6-2 is computed, and the reverse of the list [3,4,5] is computed and returned. The results of 4+3 are ignored and the pattern 4 is matched to the variable H. For ever after H will have the unchangeable value 4. "lists" is the name of a standard module (library) that provides list utility functions. The result shown from the above expression is the value of the last statement so the repl will only show [5, 4, 3] as indicated above.
Problems:
1) Write an expression that matches the pattern H2 to the reverse of the list [{1,2},{2,1}].
2) Write an expression that matches the pattern H3 to the length of the list [{1,2},{2,1}].
3) Write an expression that matches the pattern H4 to the length of the flattened version of the list [{1,2},{2,1}].

# Functions

← Expressions | guards →

## Erlang Functions

To see a function in erlang we can create the file: even_prime.erl with the following code.
The function clauses are put in the order that they are checked. First is_even_prime(2) is checked for a match. If the argument matches then true is returned. This clause ends in a semicolon because the function is not finished being defined. If is_even_prime(2) fails to match then is_even_prime(N) is tried. is_even_prime(N) is checked for a match. N is a variable that matches any integer. The statement when is_integer is a guard that admits only integer types to N. The semicolon says we have more to go. The period at the end tells us that the function is finished being defined. is_even_prime(Any) matches anything of any type and returns the value 'I prefer integer inputs'. The function is now finished. This function is a total function and should cover all possible single argument inputs.
outputs:

# guards

← Functions | Modules →

## Erlang Guards
### Guard structures

Legal guards in Erlang are boolean functions placed after the key word, "when" and before the arrow, "->". Guards may appear as part of a function definition or in "receive", 'if', "case", and "try/catch" expressions.
We can use a guard in a function definition
Example program: guardian.erl
and Fun definition
receive expression
if expression
case expression
and try/catch
You will notice that in these examples it would be clearer (in real code) to remove the guard and modify the pattern matching instead.
Literate programming note: Anonymous match variables that start with an underscore like "_" are not generally recommended. Rather, it is nice to use some descriptive variable name like "_AnyNode". On the other hand, for tutorial code like this, a descriptive variable is more distracting than helpful.

### Multiple guards

It is possible to use multiple guards within the same function definition or expression. When using multiple guards, a semicolon, ";", signifies a boolean "OR", while a comma, ",", signifies boolean "AND".

### Guard functions

There are several built-in-functions (BIFs) which may be used in a guard. Basically we are limited to checking the type with, is_type(A) and the length of some types with, type_size or length(L) for a list length.
Note: all erlang data types have a natural sort order.

# Modules
## Erlang modules

Each Erlang Programming source file
is required to be a separate module. Modules are created with the module statement.
compile with
run with
and get
"utility" is the module created by the file utility.erl
utility functions like rotate can be imported elsewhere with:
so now we do not need to use the "utility:" prefix. Importing modules is not generally recommended. This is very similar to python and Java imports.

# Errors
## Errors

We can deal with errors with throw and catch. In this example the value of an argument causes an error which causes an exception to be thrown. The function g is happy only when the argument is greater than 12. If the argument is less than 13 then an exception is thrown. We try to call g in start. If we run into trouble then the exception is caught in the "case catch" structure inside of start.
Sample program listing:

# Operators

Logical operators
Binary operators
String operators
Disjunction Guards

# Processes
## Erlang Processes and Messages

Processes are easy to create and control in Erlang.
The program chain_hello.erl builds a chain of processes as long as you like. Each process creates one process then sends a message to it. The program creates a chain of N processes which each print out "hello world!<N>" (where <N> is some integer).
Processes send messages to and receive messages from one another. Messages are read with pattern matching. The messages are matched in a fifo (first in, first out) way.
Note 1: The order of the final output depends on process scheduling.
Note 2: Time flows downward (in each vertical line, see note 1).
This is a Process Message Diagram for the execution of: chain_hello:start(1).
Program listing for: chain_hello.erl

# Timeouts
## Timeouts

Timeouts are created by the [ receive - after - end ] structure. Timeouts are measured in miliseconds so 4000 = 4 seconds. We can create a simple timer with the following program: myTimer.erl
Timeout values may be any number greater than or equal to 0, including the atom 'infinity'.

# Macros

The code makes A = [1,2,3,4,5].
Some handy predefined macros include:

# Techniques of Recursion
## Techniques of Recursion
### Simple techniques
#### Assembly-Disassembly

Often we would like to build a list using a recursive function. Perhaps we would like to reverse a list. We start with a single-argument version (the public entry point function) and use it to call the double-argument version (private), where the extra argument contains the output we wish to build. We can take the head off of the input, [H|T], as we build up the output, Build. When input is empty, we are done.
Observe the nice way that strings are actually processed as lists of chars. Syntactic sugar changes strings into lists and back.
(Here we use the assembly-disassembly technique of recursion. Johnny-Five would not approve of this technique. [Reference to the 1986 movie "Short Circuit."])
Remember, we need to bracket H because it needs to be a list when we do list concatenation with the plus-plus, '++'. T is always a list in [H|T]. H may or may not be a list in [H|T]; either way we need to give it a bracket so it behaves properly.
Compile and run.
We can reverse a string, which is really a list. We can reverse a list of integers. We can reverse a list of lists. We can reverse a list of tuples. But we cannot reverse a tuple of lists, because the top level structure is not a list.
If we wanted to be slick, we could use a guard to check the type of the argument at the entry point, then if it is a tuple, change it to a list, execute the reverse, and then change it back to a tuple on the way out.
Please note that the example is purely educational, and in real applications you should avoid appending to the list one element at a time. The correct way to build a list is using the [Head|Tail] form. Often this will cause the list to be in reverse order. To remedy that we then use the lists:reverse built-in-function. See example
Compile and run the functions to compare.
The reason behind the speed difference is in the implementation of Erlang lists as linked lists.

## Exercises

1) Write a function t_reverse(T) that reverses a Tuple, T, of size 5. (i.e. {a,b,c,d,e})
2) Write a function r_reverse(L) that recursively reverses each sublist in a list of lists, L.
3) Write a function s_reverse(L) that recursively reverses only the sublists but not the top level in a list of lists.
4) Write a function n_reverse(L) that recursively reverses sublists only if they contain integers.

# List Comprehensions
## List Comprehensions
### Intro to Comprehensions

A list comprehension is a mathematical way to construct a list. To do list comprehension we have to use a new operator "<-", "taken from".
English translation is: build a list L, with elements that have the value X*X, such that X is taken from the list [1,2,3,4]. It gives the output:
Notice that this is similar to
In fact, list comprehension provides a shorthand notation for most of the functions in the lists module.

### Simple Comprehensions

You can use them to solve equations.
output:

#### Lists version

Can you figure out the lists functions used in the above comprehension ?
How about
That is 5 functions in one succinct line. For the remainder of the examples take some time and find the corresponding lists functions that do the same thing.

#### Permutations

Here we flip two coins:
Note: strings are lists in erlang. all combinations are: output:

### Intermediate list comprehensions

An important use of List Comprehensions is to help translate Prolog-like statements into Erlang. [Why is this "important"?]
1- Erlang is a functional language designed for message passing (MIMD) parallel processing. Prolog is designed for logic programming. Sometimes a problem is most easily defined as a logical set of constraints on some set of data. If one thinks logically or thinks in constraints, or thinks in prolog, this style of list comprehensions can be a helpful way to do your tasks in erlang. There exist many useful solutions in prolog that can be moved to erlang via list comprehensions.
2- Constraint programming and logic programming are considered a higher level way to program than functions, and hence, are a good way to save you time and increase terseness.
Warning: constraint and logic based programs can be harder to debug because strict step by step actions are hidden and delegated to the list comprehension engine. Order of constraints in erlang list comprehensions can affect the output. Order dependence of constraints can be a non-intuitive distraction.
Note: in general, using huge numbers of atoms is not a good idea as they are never garbage collected.
compile with c(think). and generate output with:

### Advanced List Comprehensions

Example with quicksort in 7 lines.
(Btw: This isn't actually "quicksort," as you'd want to use it, because it uses more memory than necessary, and doesn't get the VM page/cache benefits of an in-place quicksort. But it's neat nevertheless!)

### Exercises

1) Write a program using list comprehension that finds the integer solutions {X,Y} for a circle of radius 5.

### Solutions

1)

# List Comments
## Comments

The preferred style for comments in Erlang is to use:

# Variables

Variables in Erlang
Technically there are no variables in Erlang in the sense of multiple assignment. There are Dummy Variables which can take matching values in functions. Once matched their values do not change. Variables in erlang must start with a Capital letter from the Latin 1 character set.
Examples of variables
Explanation

# Kernel and Stdlib
## Kernel and Stdlib

The kernel provides simple process-management services, module access, and garbage collection.
The Stdlib includes a large number of commonly used utility functions. Packages included in STDLIB include utilities for math, regexp, printing, various data structures (array, dictionary, tree) and process management (slave, supervisor). A list of functions available in each module can be listed with
where Mod is some module from list:

# Distribution
## Distributed Processing

Theoretically, in Erlang, writing a parallel program for many computers is not much different from writing a program for a single computer. Each process on each processor has a unique id/name. Processes can be easily spawned. Messages can be easily sent and received. Each home directory on each computer will have a special Erlang cookie password file that allows access to Erlang processes on that machine.
The major problems people have writing distributed programs in Erlang are general network reachability issues related to firewalls and routers. you can make communication between two or more distributed node over network. if you want to communicate with node B from node A. then you can send message to node B as it is local process. you must specify node name to communicate such as:{pid,Nodename}!'hello node A'. where pid is process identifier of process on node B. to more generalization you should register name of the process. for example:register(pro,self). now you can use pro in place of self.

# Behaviors
## Behaviors

In Erlang, a behavior is a design pattern implemented in a module/library. It provides functionality in a fashion similar to inheritance in object-oriented programming or interfaces in Java. A number of callback functions must be defined for each behavior to work.
Examples of behaviors are:
* client-server
* event-handler
* gen-server :gen_server
* hot-standby
* keep-me-alive
* supervision-tree
* upgrade-handler
* worker-supervisor
A behavior can be activated with the following code (note: you can use "behavior" instead, if you feel American):

# Design Principles
## Design Principles
### Send Messages, do not share memory

Messages are sent between processes. The compiler is very picky about what operations are "parallel-safe" and is not shy about letting you know. The compiler is particularly picky (parallel-safe) about sending and receiving messages. If you recurse after each message is processed then your code is more parallel-safe. Messages are delivered in order and are selected for removal from the queue by pattern matching (as in Prolog). Because of the extensive built-in pattern matching, Erlang operates in a declarative way. Because of the parallel-picky compiler, it is often as easy to write a parallel program in Erlang as it is to write a serial program in other languages, once you get the hang of the language.

### Fail Early and Often

Erlang designers often use an unusual but effective design technique called "fail early and often", FEO. Let processes fail. If unexpected inputs arrive, then let the process crash, and restart it. This allows for terse code that is robust. We do not waste time coding for bad inputs. We code to expected inputs(the specification only). Theoretically, this technique should make for improved security because unexpected inputs cause processes to self destruct and errors and bad behaviour do not propagate.

### Debugging

Once a process has crashed we can gather crash information and let the programmer fix problems early. If a process is written to specification, and it crashes then the only possible problem is that it received bad input.

# Testing
## Testing

The recommended order of testing for an Erlang program is:
* Test on one core in one microprocessor.
* Test on multiple cores.
* Test on multiple computers (if needed).

# Documentation
## Documentation

Comments
The preferred comment style in erlang is to use:

# Records

Records in Erlang are syntactic sugar for tagged tuples. The functionality is provided by the preprocessor, not the compiler, so there are some interesting restrictions on how you use them and their support functions.

## Defining Records

The code above defines a record called myrecord with two elements: "first_element" and "second_element". From now on we can use the record syntax #myrecord.

## Equivalent to Tuples

Records are syntactic sugar for tuples.
The record we defined with two fields is equivalent to a tuple with a tag (the name of the record) and as many elements as the record has fields—two, in our case.

# Additional Types
## Additional Types

We have already seen the following types: tuple, list, integer, float, function and pid. We can check the type of an object by testing it.
If you wish to convert between types, lists are the lingua franca of types in Erlang so make it a list first on your way to something else. Remember, type conversion is not a parallel-safe operation.
Some additional types are: port and reference.
A port is a connection to the external world. Typically ports generate and/or consume bit streams. Binary data is considered untyped data in Erlang. (See BitSyntax).
A reference is a globally unique symbol and is generated with:
A reference is only useful when a unique tag is needed across all connected processes. Do not confuse the term reference with a references in C, which points to data. An Erlang reference is only a unique tag.

### Erlang Has No Boolean Type

Erlang has no Boolean type. It has the atoms (true and false) which are generated by certain functions and expected by certain functions like guards and list comprehensions. The function: is_constant generates either true or false.
We can test whether an object is a constant.
Because atoms are represented as constant numbers, atoms are constants.
Theoretically, because the Boolean type is not built in, it should make it easier to let Erlang compute with alternate types of logic, {true, false, null} for instance.

# Function Objects
## Function Objects

Function objects can be named or unnamed, or stored in a variable. Function objects can be like lambda expressions. Lambda expression in Erlang are created with the keyword "fun". Lambda expressions are unnamed functions that can be stored in variables. Please consider the following:
Sample Erlang command line code:
Generic behaviors often use function objects to become specialized. A generic server can be dynamically given a function object to allow it to become a particular type of server or service provider.

# Bitsyntax
## Bit Strings

Erlang lets us use Bit Strings. They have the form
The default bit length is 8.
Integers used in bit strings can be padded on the left with zeroes.
Some bit strings have string-like representations.
Remember that using the default bit length will cause truncation of too-large integers!
We cannot specify individual bits with integers. We must use values with a bit length of one.
We can select parts of a bit string with pattern matching.
We can match X to a value.
We can not match Y to a bit length.
We can use a bound variable as a bit length.

# Example1

Objects with Erlang
Erlang is a functional programming language and a concurrency oriented programming languages (Armstrong, dissertation, 2005), but Erlang does not have explicit built-in object oriented language features. An object oriented programming style can be achieved by alternative means easily. It is particularly easy to do object oriented programming if we restrict ourselves to single inheritance. One can use processes to represent classes and messages to represent methods. To do so, each object when created can create a chain of processes that represent their ancestors in the inheritance chain. The methods(messages) can be passed up the chain until they reach a process that has a matching method. If the message reaches the top of the chain(the Object class or above that dev_nul) then we can generate an exception for a "bad method name". Each class(process) will maintain its own attributes(variables) in its own recursive argument call list. These attributes can be accessed and updated with messages such as get and set. Attributes are stored in a dictionary called a Bundle, in each class process.
Included is some example code that creates OOP using the described technique. In the program, we create an instance of the class integer. Its parent float, knows how to take the square root of reals. Its parent complex, knows how to take the square root of negative numbers. Its parent matrix, knows how to take the square root of a diagonal matrix.
Logically, the traditional class relationship is held in the class diagram. An integer is a Real. A Real(float) is a (subset of) complex. An a complex number is a (subset of) complex matrices, if we think of a (1 by 1) matrix as a single number.
A message(method) is sent to an instance of an object. If a process does not know how to do something, it passes a message(method) to its parent(process in this situation). If we tried to do something like take the sqrt(non-diag-matrix) it would be passed up to dev_nul and generate an error.
The start function creates an instance of the integer class. Then it asks the instance to calculate the square_root of 4 numbers: 4, 0.04, -4 and the matrix [[4,0],[0,9]]. The answers are: 2, 0.2, {2, i} and [[2,0],[0,3]].

# Using lists
## foreach

produces no output because the purpose of foreach is to generate side-effects. However,
does work, because io:format is a side effect function.

## sequence of numbers

lists:seq(1,100) is like range(1,101) in python.

## sort

lists:sort( A ) is what you think.

# Regular Expressions

The regular expression, "w.+d" matches the string, "hello world" at location 6 for 5 chars.
Makes a substitution, replacing "203040" with "01".

# Debugging and Tracing
## Tools

* Debugging
** dbg
** debugger
* Tracing
** ttb
** invision
** et
* Coverage
** Cover

### Coverage

Coverage shows what functions are covered by a test. Sample program: test_rotate.erl
Sample output:
Contents of cover.html shows that each clause was run once except for left_rotate(). Each time the program is tested, the run count for each visited clause is increased by one. Cover sample output file:

# Performance and Optimization
## Profiling

There are a number of profiling libraries available:
* cprof
* eprof
* fprof
Profiling of any kind has a runtime performance penalty - the reason for the different libraries above is their different trade-offs in terms of profiling precision and the performance penalty for using them.

# Unit Testing with eunit
## Installing eunit

This section will show you how to install eunit on different operating systems. Once you have installed eunit its use is fairly consistent across the different operating systems.

### ubuntu

Get source with:
Compile code with:
Copy to /usr/lib/erlang/lib

### Test the Installation

To test that everything is installed ok before writing any tests create a file test01.erl with the following contents:
Compile this file as follows:
If you get the result {ok,test01} then you've installed eunit correctly.

## Using eunit

We'll start by writing a passing test and a failing test. In the file you created to check the installation add the following:
Run the tests as follows.

# Databases in Erlang
## Dictionary

Data can be stored in many ways in Erlang. Each process has a local dictionary that uses put and get.

## ETS

Data can be stored with the ETS (Erlang table storage system) via the ETS library. It creates data at the process level. See Using_Ets.

## Mnesia

Mnesia is a distributed database that lives in the local file system.

## External Databases
# ETS local data storage

ETS is the Erlang table storage system, which provides hash-based data storage and access functions. These functions run in constant time. ETS data is stored in a process as long as it is running.
Here is an example of how to use some simple functions in ETS. Notice that the table is not square because goofy has no last name.

## Sample program: test_ets.erl
# Using mnesia
## Using Mnesia

Mnesia is the distributed database written in Erlang, meant to mainly be used by Erlang programs. Simple queries can be written with query list comprehensions (qlc). Realtime queries can decide to not use transactions.

### Explain program: art.erl

The program defines some functions that work similar to SQL. We wish to build a table of artwork named "painting", with fields: index, artist, and title.
art:init. Starts the database and creates the table: painting.
insert Puts data into the table
select Gets data out of the table
Note that the second time we call init the database is restarted but we get an error when it tries to recreate the table (as it already exists).

### Sample output: art.erl
# Autonomous Agents
## Autonomous Agents
### Dynamic timeout based initiative switching
#### Explanation of the code in jungle.erl

Here we have a simple chat-bot agent called person/4. We create two instances of it called Tarzan and Jane. They talk to each other. Each has a timeout. The timeout is the length of time one will wait before they initiate conversation. The initial timeout of Jane is set to 10 seconds. The initial timeout of Tarzan is set to 8 seconds. Because of the initial values, Tarzan will speak first and Jane will respond. Both timeouts start over but keep the same values. Again, Tarzan speaks first and Jane responds. Now things get interesting. The agent can tell if the conversation is repeating. If the conversation repeats then special messages are sent to cause a swap in the relative levels of timeout. Now Tarzan waits longer than Jane and Jane has a chance to speak first. Now, Jane speaks first twice. Then they swap initiative again. Since the processes are autonomous, we need to stop them with a quit program called jungle:quit. Note: the change in timeout length is either double or half. The timeout change is similar to the exponential binary backoff for ethernet collisions. External link: Exponential_backoff.

#### Sample output from: jungle.erl
# Parallel Programming
## Prime Sieve (parallel with linda type coordination)

Linda is a way to coordinate the actions of multiple processors. A tuplespace is created for the candidate primes to live. The sieve processes are created and send messages to the tuplespace to remove non-primes. The sieve processes also send messages to each others to remove the non-prime sieves.
How many processors can this program use? This program creates as many sieves as the square root of the numbers in the matrix (tuplespace).
If we are looking for the primes below 100 then there are about 10 parallel sieve processes. Actually, most of the sieve processes are halted and only (the number of prime numbers under the square root of Max) processes are left at the end. This allows an easy parallelism of 10 for 100 and 100 for 10000 with little modification.
In Erlang, it is not recommended that one use a huge number of atoms, so N should not get too large. We also might run out of processes or memory.
This program breaks one of the general rules of Erlang process management: do not use peer managers. Each of the sieve processes is a peer manager because each sieve may halt any other sieve. Rather, processes should be managed in a top-down tree structure. The peer management of the sieves causes some nasty timing issues. Timing is one reason why peers are usually a bad idea.
When the sieve for 2 ends, the list of primes is dumped. Erlang should give each process equal CPU time. When the slices are even, the sieve for 2 starts first and ends last. When some other sieve is starved for time, it may end after sieve 2 and the prime number dump will be too early, leaving some numbers divisible by 2 in the list of putative primes. Relative starvation of some process happens about 1 out of 10 times. Clearly the critical word should be: "tries". "Erlang TRIES to give each process equal time slices."
Does it hurt to have non-prime sieves running? We can use a 6-sieve. A 6-sieve is redundant because the 2-sieve and the 3-sieve remove all numbers that the 6-sieve would remove. By removing the 6-sieve and its non-prime sieve brothers we reduce the number of messages that the matrix must handle thereby speeding the final result.

#### Prime Sieve Program (parallel)
### Sample Output for Prime Sieve
# Making Parsers with yecc

Making Parsers with yecc
Yecc is an erlang version of yacc/bison.
We have a BNF(Backus-Naur_form) grammar in a source file ending in .yrl, yrl means yecc rule list. We can parse a simple xhtml file using yecc. Actually, we will apply yecc to html.yrl to create a parser called html_parser.erl. Next we use the html_parser to parse some xhtml, voila.
All tags in the xhtml code must have matching open and close. (Of course a more powerful way to parse an xml file in erlang is to use xmerl).
html.yrl source:
It can be a pain to build and run a parser each time we edit the source yrl file. To speed things up, we can use a program to build and run the parser for us. We compile and run the test program which builds the parser and tests it for us on some document.

# Creating Web Applications with yaws

Yaws is one of the popular web servers programmed in Erlang. The goals of Yaws is to be a feature rich web server with a multitude of options for the user to configure and deploy their web applications with.
| Basic Yaws Getting set up First Yaws Webapp The out/1 function The Arg structure The API | Elementary Yaws Writing an appmod Writing a yapp Extending Yaws |

## Additional Resources

* Yaws official website
* Erlang official website
* Erlang documentation

# Using Erlang with Emacs

Erlang mode for emacs -http://www.erlang.org/doc/man/erlang_mode.html -http://www.erlang.org/doc/apps/tools/erlang_mode_chapter.html
You can use Distel on top of this, for extra functionality. http://code.google.com/p/distel/

# Erlang Resources

* Open Source Erlang - Official site
* Documentation - Comprehensive documentation and user's guide for Erlang/OTP R11B
* Erldocs - Erlang documentation alternative with filter/search function and better interface
* trap_exit - Forum and wiki about Erlang
* Jungerl - Collection of free Erlang software

## Large Projects Built with Erlang

* CouchDB - Document oriented database
* ejabberd - A large volume Jabber/XMPP IM server.
* Wings 3D - A 3D modeller (Wikibook manual: Wings 3D)
* wxErlang - A GUI API
* Yaws - A web server (Wikibook manual: Yaws)
* Disco - An implementation of the Map-Reduce framework
* Zotonic - The Erlang Web Framewoork & CMS

## Erlang related projects

* Erlide - An erlang IDE plugging for Eclipse