Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Functions and Pattern Matching

Functions and Clauses

Learn how Erlang functions work: clauses and heads, arity, the last expression as return value, multiple clauses, private helpers and function references.

Functions are the heart of Erlang. There are no loops, no classes and no mutable variables, so almost everything you build is a function calling other functions. This lesson explains how a function is defined, why it can have several clauses, and how names, arity and exports fit together.

Anatomy of a function

ERLANG
-module(math_utils).
-export([square/1, add/2]).

square(X) ->
    X * X.

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

A function definition has a head (square(X)), an arrow -> and a body after it. The body is one or more expressions separated by commas, and the whole definition ends with a period. The value of the last expression is the return value. There is no return keyword.

ERLANG
stats(List) ->
    Sum = lists:sum(List),
    Count = length(List),
    Average = Sum / Count,
    {Sum, Count, Average}.

The body runs the expressions in order, each separated by a comma, and returns the tuple. A comma means "and then", a semicolon means "or else try the next clause", and a period means "end of the function".

Name and arity

A function is identified by its name and arity (the number of parameters). area/1 and area/2 are different functions that happen to share a name; they may have unrelated behavior. The compiler treats them separately and you export them separately:

ERLANG
-export([area/1, area/2]).

area(Side) -> Side * Side.
area(Width, Height) -> Width * Height.

This is how Erlang offers default values: a shorter version calls the longer one.

ERLANG
greet(Name) ->
    greet(Name, "Hello").

greet(Name, Greeting) ->
    io:format("~s, ~s!~n", [Greeting, Name]).

Multiple clauses

A function may have several clauses, separated by semicolons. Erlang tries them top to bottom and runs the first one whose head matches the arguments.

ERLANG
describe(0) -> zero;
describe(1) -> one;
describe(N) when N < 0 -> negative;
describe(_) -> many.
ERLANG
1> describe(0).
zero
2> describe(-5).
negative
3> describe(42).
many

The when N < 0 part is a guard, an extra condition on the clause; see case, if and guards. The last clause with _ is a catch-all. The order matters: put specific clauses first.

If no clause fits, the call fails with function_clause:

ERLANG
1> describe_only_zero(5).
** exception error: no function clause matching mod:describe_only_zero(5)

Often that crash is exactly what you want. The "let it crash" style prefers an immediate error over silently returning a wrong value.

All clauses of one function must be next to each other and have the same arity. Mixing f/1, then g/1, then more f/1 clauses is a compile error.

Private and exported functions

Functions not listed in -export can only be called from inside the same module. Use them as helpers:

ERLANG
-module(report).
-export([print/1]).

print(Items) ->
    lists:foreach(fun print_line/1, Items).

print_line({Name, Price}) ->
    io:format("~-10s ~6.2f~n", [Name, Price]).

print_line/1 is private. The expression fun print_line/1 creates a function value from it, and fun lists:sum/1 references an exported function from another module. A call report:print_line(X) from outside fails with undef.

Calling functions

Inside a module call a local function by name: square(5). For another module use module:function(Args), a remote call. A fully qualified call to the current module (?MODULE:square(5)) also works and has a special property: it always uses the newest loaded code, which matters for hot code loading.

Arguments are evaluated before the call, left to right, and are passed by value (immutable data is simply shared). There is no way to modify an argument in the caller.

Expressions everywhere

In Erlang almost everything is an expression that has a value: function calls, case, if, receive. A function body may be a single large case:

ERLANG
sign(N) ->
    case N of
        0 -> zero;
        _ when N > 0 -> positive;
        _ -> negative
    end.

Documenting functions

The convention is a -spec attribute with types plus a comment. Specs help readers and the Dialyzer tool:

ERLANG
-spec square(number()) -> number().
square(X) ->
    X * X.

-spec does not change how the function runs, it documents it and enables static analysis. You will use it in the tools and testing chapter.

Stand-ins in JavaScript

These show clauses and arity in JavaScript. They are not Erlang.

JS Stand-in: arity-based dispatch (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: clauses, guards and function_clause (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What separates clauses of the same function?

    Clauses are separated by semicolons; the last clause ends with a period.
  2. 2. What is the return value of an Erlang function?

    There is no return statement. The body's last expression is the result.
  3. 3. Are area/1 and area/2 the same function?

    Name and arity together identify a function.
  4. 4. What error occurs when no clause matches the arguments?

    A call that fits no clause raises a function_clause error.

Summary

  • A function has a head and a body; commas separate expressions, semicolons separate clauses, a period ends it.
  • The last expression is the return value.
  • A function is identified by name and arity; defaults are made with a shorter function calling a longer one.
  • Clauses are tried top to bottom; no match raises function_clause.
  • Unexported functions are private helpers; fun name/arity makes a function value.

Next: Pattern Matching