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).