Introduction

Erlang

Prominent applications

History lesson

Essence

Sequential aspects

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

Expressions

Interpreter

$ erl
Erlang/OTP 18 [erts-7.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V7.0  (abort with ^G)
1> 3 + 5.
8
2>

Evaluation of expressions

3 + (2 * 4)3 + 811

Precedence

Task: You want to check how is the expression ? andalso ? orelse ? decoded: is it (? andalso ?) orelse ? or ? andalso (? orelse ?) ? In other words, is the precedence of andalso higher than that of orelse? Design an experiment that will confirm one or the other.

Additional question: can the experiment really confirm it?

Functions

% This is a comment
g(N) -> N + 2.

Evaluation of functions

1> g(3) * g(1).
15
2>

g(3) * g(1)(3 + 2) * g(1)5 * g(1)5 * (1 + 2)5 * 315

Multiple clauses

h(2) -> 4;
h(3) -> 6;
h(N) -> N - 1.

Repeated variables

myequal(N, N) -> true;
myequal(N, M) -> false.

Guards

h2(1)            -> 1;
h2(N) when N < 5 -> 3;
h2(N)            -> N + 1.

Recursion

code

sum_m_n(M, N) when M > N -> 0;
sum_m_n(M, N)            -> M + sum_m_n(M+1, N).

sum_m_n(2, 4)

2 + sum_m_n(3, 4)

2 + (3 + sum_m_n(4, 4))

2 + (3 + (4 + sum_m_n(5, 4)))

2 + (3 + (4 + 0))

2 + (3 + 4)

2 + 7

9

Tail-recursion

% The same function reimplemented using tail-recursion
sum_m_n_i(M, N, Acc) when M > N -> Acc;
sum_m_n_i(M, N, Acc)            -> sum_m_n_i(M+1, N, Acc + M).

% We define a convenience function
sum_m_n_i(M, N) -> sum_m_n_i(M, N, 0).

sum_m_n_i(2, 4)

sum_m_n_i(2, 4, 0)

sum_m_n_i(3, 4, 0 + 2)

sum_m_n_i(3, 4, 2)

sum_m_n_i(4, 4, 2 + 3)

sum_m_n_i(4, 4, 5)

sum_m_n_i(5, 4, 5 + 4)

sum_m_n_i(5, 4, 9)

9

Multiple statements, variables

f(X) -> X * 2.

g(N) ->
  Y = f(N-1),
  Y + 2.

g(5)

Y = f(5-1),
Y + 2

Y = f(4),
Y + 2

Y = 4 * 2,
Y + 2

8 + 2

10

Data types

Modeling data

{shape, {triangle, 2, 2, 3}, blue}
{shape, {square, 3}, red}
{shape, {rectangle, 3, 4}, white}
data Tree a = Leaf a | Node (Tree a) (Tree a)

Pattern matching

More pattern matching

Even more pattern matching

Consuming lists

Note: [a, b, c] is the same as [a | [b, c]]

len([a, b, c])

1 + len([b, c])

1 + (1 + len([c]))

1 + (1 + (1 + len([])))

1 + (1 + (1 + 0))

1 + (1 + 1)

1 + 2

3

len_i([a, b, c])

len_i([a, b, c], 0)

len_i([b, c], 0 + 1)

len_i([b, c], 1)

len_i([c], 1 + 1)

len_i([c], 2)

len_i([], 2 + 1)

len_i([], 3)

3

List examples

code

Adding elements of a list

More examples

Side effects

Case statements

area({square, 3})

case {square, 3} of
{square, Side} -> Side * Side;
{circle, Radius} -> Radius*Radius*math:pi()
end

3 * 3

9

If statements

  f(X) ->
    if X > 2 -> X + 2;
       true  -> X - 2
    end.
  

Modules

code

Data types (Records)

A note on the use of records and functions



Concurrent Programming 2016 - Chalmers University of Technology & Gothenburg University