Er, mind your language

Erlang Programming by Francesco Cesarini and Simon Thompson

Erlang has always sounded like an interesting language to learn. A functional language with an emphasis on concurrent processes and fault tolerance, which has been used in various bits of telecoms software for many years. This book proved to be a really good introduction. It covers both the language and the associated runtime system, showing the implementation of a number of reasonably sized examples.

I thought it would be good to write up a quick summary of Erlang. We’ll show what happens when we type things at the read-eval-print-loop (REPL). The most basic data types are atoms (items starting with a non-capital letter), strings, integers and floating point values. Tuples are represented by enclosing comma separated items in {}.

15> {hello, "hello", 1, 2.3}.

Items starting with a capital letter are variables. These are assigned using pattern matching.

22> {Var1, Var2, 1, 2.3} = {hello, "hello", 1, 2.3}.
23> Var1.
24> Var2.

Once a variable is bound, its value is used in the pattern matching.

25> Var1 = "bong".
** exception error: no match of right hand side value "bong"
28> {Var1, Var2} = {"a", "b"}.
** exception error: no match of right hand side value {"a","b"}

Code is packaged as a set of match expressions and results. We could write a source file, fact.erl, containing the following module definition.

fact(0) -> 1;
fact(N) -> N * fact(N-1).

We can then go to the relevant directory and compile and load the module into the running Erlang session.

29> cd("c:/users/clive/desktop/erlang").           
30> c("fact").                                     
31> fact:fact(10).                                 
32> fact:fact(20).

There’s also a list datatype, which can be pattern matched using a Prolog type syntax.

34> [P|Q] = [1,2,3].
36> P.
37> Q.

Of course, the really impressive thing about Erlang is that the process is very much a first class concept.

-export([fact/1, factorialServer/0]).

fact(0) -> 1;
fact(N) -> N * fact(N-1).

factorialServer() ->
    {X, Pid} -> Pid ! {ok, fact(X)}, factorialServer();
    stop -> {}

The key idea is that every Erlang process has a mailbox into which messages are delivered. Messages are sent using the ! method which takes a process id and sends it the message which is often a tuple. This tuple will typically contain the pid of the caller, allowing a response to be delivered. The server is typically implemented as a self tail-recursive function which uses receive with a set of match clauses. Receive causes the system to scan the mailbox messages to find the first that matches, at which point the message is removed from the mailbox and the corresponding result expression is evaluated. This method of processing means that the messages are processed one at a time, and hence there is no user level locking to guard against concurrent execution.

We can compile this in the shell, and then spawn a new process that runs the factorialServer function.  flash() is a function we can call in the shell to print out all of the messages in the shell process mailbox.

45> c("fact").
46> Pid = spawn(fact, factorialServer,[]).
47> Pid.
55> Pid ! {20, self()}.                  
56> flush().
Shell got {ok,2432902008176640000}

The language contains lots of support for functional programming, including anonymous functions.

4> (fun (2) -> 1; (Bar) -> 2 end)(2).
5> (fun (2) -> 1; (Bar) -> 2 end)(3).

There’s tons more to the language, but I’ll recommend you go and read the book. There are various standard libraries for collections and list manipulation. There are ways for processes to monitor other processes, so they can deal with failure. There are ways to dynamically reload code modules. There are ways to pass binary data around, and easy ways to get processes communicating using sockets. There are various debugging tools and libraries for producing GUIs.

Erlang seems to me to be an undiscovered gem, and this book covered tons of very interesting material. A great read.

This entry was posted in Books. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s