Erlang
Erlang is a functional language and is a very easy language to use to get used to Parallel Computing. Especially the concept of message passing. Below are some core features of Erlang that make it easy to use for concurrency.
- Variables are immutable.
- Prevents shared mutable state β safer for concurrency.
- Erlang is built around message-passing concurrency.
- Processes communicate via
send
andreceive
. - Processes cannot corrupt each otherβs state..
- Processes communicate via
The Erlang Shell
Erlang has its own shell where bits of Erlang code can be written directory and evaluated.
You can start the Erlang shell by running erl
.
1> 2 + 5.
7
2>
The above code executes an expression and evaluates it. The Erlang shell has line numbers.
You can terminate the Erlang shell by pressing ctrl+c
and then pressing a
or by running halt()
in the shell.
Modules and Functions
Obviously having a programming language run in the shell is not very good so you can write Erlang files.
When you write an Erlang file, you can compile it by running c(<filename>)
(without the extension) in the shell. For example, running c(file)
compiles a file called file.erl
.
-module(tut).
-export([double/1]).
double(X) ->
2 * X.
Here is an example Erlang file which we'll call tut.erl
. You can run the function after compiling the file by executing tut:double(2)
in the Erlang shell.
Each Erlang file must contain an Erlang module. The first module listed is always the module name.
The export
line says it this module contains a function called double
and it takes one argument.
Functions can also have multiple parts. For example, the function below which calculates the factorial of a number:
fac(1) ->
1;
fac(N) ->
N * fac(N - 1).
As two parts to the fac
function. If the argument passed into fac
is a 1, just return 1, else continue calculating the factorial.
Atoms
Atoms are another data type in Erlang. Atoms start with a small letter like charles
or inch
. Atoms are simply names and nothing else and unlike variables can not hold a value.
They can be useful if you want to call/reference a specific clause of a function.
convert(M, inch) ->
M / 2.54;
convert(N, centimeter) ->
N * 2.54.
Here, inch
and centimeter
are atoms that can be passed into the convert
function. If you were to pass in something other than those two atoms, it will throw an exception.
Tuples
Tuples are surrounded by curly braces {}
and are used to group elements together. They can have as many parts as you want. Think of them as similar to Python tuples.
Tuples have a fixed length on the number of items and are not mutable.
Lists
Lists in Erlang are surrounded by square brackets []
and are different from tuples in the fact that they represent things as lists rather than just groups of things.
In Pattern Matching - Erlang, the vertical bar |
is used to denote the rest of the list.
ex. [A | B] = [1, 2, 3, 4]
B is assigned [2, 3, 4]
which is the rest of the list.