Erlang Variables

Erlang Variables

Dynamic Datatyping
Erlang is a dynamic datatyping programming language. That means that when “declaring” a variable you do not need to statically specify the datatypes. For example, this is how we declare and initialize an integer in Erlang:

1
I = 17.

This approach has both advantages and disadvantages. Advantages: when programming, it is fast and convenient as we don’t need to declare the variables datatypes. Disadvantages: In big projects it can lead to code readability problems unless well documented.

Variables Declaration
Erlang is influenced by Prolog. As with Prolog variables is a string consisting of letters, numbers and underscore characters, and beginning with an upper-case letter or underscore.

Example:

1
2
3
4
5
6
7
X
Name1
PhoneNumber
Phone_number
_
_Height
[H|_] = [1, , 2, 3]

Variable Assignement
Another feature that Erlang inherited from Prolog is binding with pattern matching. In a nutshell, a value is not assigned to a variable but bound with pattern matching. The most important thing is that variables in Erlang are single assignement, it mean that once bound to a value, their value cannot change for their lifetime.

Example (open terminator and try the following):

1
2
3
1> Age = 10.
10
2> Age = 11.

We will get an error:

** exception error: no match of right hand side value 11

The problem is that A is bound to the value 10, so Erlang tries to pattern match 10 with the value 11 which is impossible.