Introduction

Erlang

Typical applications

History lesson

Essence

Sequential aspects

We cover the following aspects. Click on the links for further information.

Data types

Data types (Records)

Modeling data

data Tree a = Leaf a | Node (Tree a) (Tree a)

Variables

A_long_variable_name

Functions

Evaluation strategy

factorial(3) 
==
3 * factorial(3 - 1) 

It now evaluates the argument of the function *, which implies evaluating factorial(3 - 1). For that, Erlang firstly evaluates the argument of the function (eager evaluation strategy).

factorial(3) 
==
3 * factorial(2)

As before, Erlang applies the second clause with N = 2.

factorial(3) 
==
3 * (2 * factorial (2 - 1))

Erlang then reduces the argument of factorial.

factorial(3) 
==
3 * (2 * factorial (1))

Now, the second clause with N = 1 gets applied as follows.

factorial(3) 
==
3 * (2 * (1 * factorial (1 - 1))

Finally, we obtain

factorial(3) 
==
3 * (2 * (1 * factorial (0))

and Erlang can then apply the first clause.

factorial(3) 
==
3 * (2 * (1 * 1))

By definition of *, we have that

factorial(3) 
==
6

as expected.

Pattern matching

More pattern matching

Even more pattern matching

Modules

code

List examples

code

Adding elements from a list

More examples

Tail recursion

code

A note on the use of records and functions

Concurrency


Processes

code

start() ->
     Pid = spawn(fun run/0),
     io:format("Spawned ~p~n",[Pid]).

run() ->
 io:format("Hello!~n",[]).

Forking

BIF

Message passing

How does it work?

Forms of synchronization

Consider the behaviour of the sender of a message

Examples

Forms of naming

How do sender and receiver refer to each other when message passing is used?

Erlang message passing

Spawning and tail recursion

A simple echo-server

code

Indirect

-module(echo).
-export([start/0]).

echo() ->
    receive
    {From, Msg} -> 
        From ! {self(), Msg},
        echo();
    stop ->
        true
    end.

start() ->
    Pid = spawn(fun echo/0),
    % sending tokens to the server
    Token = 42, 
    Pid ! {self(), Token},
    io:format("Sent~w~n",[Token]),
    receive 
       {Pid, Msg} ->
            io:format("Received ~w~n", [Msg]) 
    end,
    % stop server
    Pid ! stop.