Category Archives: Erlang

Erlang modules and functions

Modules

Modules are (what you might expect) a way to group together functions.

We declare a module with the first line

-module(Name).

This is always the first line of a module and the Name is an atom (an atom being a literal/constant).

Next up in our module, we’ll be exporting functions along with their arity (arity being an integer representing the number of arguments that can be passed to the function). So for example, if we have add with two arguments we would export it like this

-export([add/2]).

We can export multiple functions within the -export for example

-export([add/2, delete/2, multiply/2, divide/2]).

So let’s put those pieces together and we get a math module something like this

-module(math).
-export([add/2, subtract/2, multiply/2, divide/2]).

add(A, B) -> 
    A + B.

subtract(A, B) -> 
    A - B.

multiply(A, B) -> 
    A * B.

divide(A, B) -> 
    A / B.

Functions

So we’ve seen some example of functions, let’s look at the syntax.

Functions take the form Name(Args) -> Body. where each expression in the body ends with a comma, so for example

start() -> 
    S = "Hello World",
    io:fwrite(S).

Installing Erlang on Ubuntu 20.x

The steps below are taken from the sites listed in the reference, recreating here for my reference.

Installing

sudo apt update
sudo apt install software-properties-common apt-transport-https
wget -O- https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc | sudo apt-key add -
echo "deb https://packages.erlang-solutions.com/ubuntu focal contrib" | sudo tee /etc/apt/sources.list.d/erlang.list
sudo apt update
sudo apt install erlang

Checking it all worked

Let’s check if everything worked. You can just run

erl

from your terminal OR let’s write the good ol’ hello world by create helloworld.erl and add the following code

-module(helloworld). 
-export([start/0]). 
start() -> io:fwrite("Hello World\n").

Run this using

erlc helloworld.erl
// then
erl -noshell -s helloworld start -s init stop

If all went well you’ll see Hello World written to standard io.

To add the last bit of the How to Install Erlang in Ubuntu post, to remove Erlang run

sudo apt remove erlang
sudo apt autoremove

References

How To Install Erlang on Ubuntu 22.04|20.04|18.04
How to Install Erlang in Ubuntu