Functions in Erlang

Functions are central in Erlang. We’ll learn about functions with a few different examples.

-module(functions).
-export([main/0, plus/2, plus_plus/3]).

% Here's a function that takes two integers and returns
% their sum as an integer.
plus(A, B) ->
    % Erlang uses the last expression as the implicit return value,
    % so we don't need an explicit return statement.
    A + B.

% In Erlang, we define each function clause separately,
% so there's no need to omit type declarations for similar parameters.
plus_plus(A, B, C) ->
    A + B + C.

main() ->
    % Call a function just as you'd expect, with name(args).
    Res1 = plus(1, 2),
    io:format("1+2 = ~p~n", [Res1]),

    Res2 = plus_plus(1, 2, 3),
    io:format("1+2+3 = ~p~n", [Res2]).

To run this Erlang program:

$ erlc functions.erl
$ erl -noshell -s functions main -s init stop
1+2 = 3
1+2+3 = 6

In Erlang, functions are defined within modules. We define the module name at the top of the file and export the functions we want to make publicly available.

Erlang uses pattern matching for function definitions, so we define each function clause separately. This approach provides a clean way to handle different arities or patterns of arguments.

Erlang is a functional programming language, so it doesn’t require explicit return statements. The value of the last expression in a function is automatically returned.

There are several other features to Erlang functions. One is pattern matching in function heads, which we’ll look at in more detail in future examples.