Cover by Francesco Cesarini, Simon Thompson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Variables

Variables are used to store values of simple and composite data types. In Erlang, they always start with an uppercase letter,[6] followed by upper- and lowercase letters, integers, and underscores. They may not contain other “special” characters. Examples of variables include the following:

A_long_variable_name Flag Name2 DbgFlag

Erlang variables differ from variables in most conventional programming languages. In the scope of a function, including the Erlang shell process, once you’ve bound a variable, you cannot change its value. This is called single assignment. So, if you need to do a computation and manipulate the value of a variable, you need to store the results in a new variable. For example, writing the following:

Double = 2,
Double = Double * Double

would result in a runtime error, because Double is already bound to the integer 2. Trying to bind it to the integer 4 fails as it is already bound. As mentioned, the way around this feature is to bind the results in a fresh variable:

Double = 2,
NewDouble = Double * Double

Single assignment of variables might feel awkward at first, but you’ll get used to it very quickly. It encourages you to write shorter functions and puts in place a discipline that often results in code with fewer errors. It also makes debugging of errors related to incorrect values easy, as tracing the source of the error to the place where the value was bound can lead to only one place.

All calls with variables in Erlang are call by value: all arguments ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required