A function declaration is a sequence of function clauses separated by semicolons, and terminated by period (.).
A function clause consists of a clause head and a
clause body, separated by
A clause head consists of the function name, an
argument list, and an optional guard sequence
beginning with the keyword
Name(Pattern11,...,Pattern1N) [when GuardSeq1] -> Body1; ...; Name(PatternK1,...,PatternKN) [when GuardSeqK] -> BodyK.
The function name is an atom. Each argument is a pattern.
The number of arguments
A function named
A clause body consists of a sequence of expressions separated by comma (,):
Expr1, ..., ExprN
Valid Erlang expressions and guard sequences are described in
Example:
fact(N) when N>0 -> % first clause head N * fact(N-1); % first clause body fact(0) -> % second clause head 1. % second clause body
When a function
If the function is found, the function clauses are scanned sequentially until a clause is found that fulfills both of the following two conditions:
If such a clause cannot be found, a
If such a clause is found, the corresponding clause body is evaluated. That is, the expressions in the body are evaluated sequentially and the value of the last expression is returned.
Consider the function
-module(m). -export([fact/1]). fact(N) when N>0 -> N * fact(N-1); fact(0) -> 1.
Assume that you want to calculate the factorial for 1:
1> m:fact(1).
Evaluation starts at the first clause. The pattern
N * fact(N-1) => (N is bound to 1) 1 * fact(0)
Now,
1 * fact(0) => 1 * 1 => 1
Evaluation has succeed and
If
If the last expression of a function body is a function call, a tail recursive call is done. This is to ensure that no system resources, for example, call stack, are consumed. This means that an infinite loop can be done if it uses tail-recursive calls.
Example:
loop(N) -> io:format("~w~n", [N]), loop(N+1).
The earlier factorial example can act as a counter-example.
It is not tail-recursive, since a multiplication is done
on the result of the recursive call to
BIFs are implemented in C code in
the runtime system. BIFs do things that are difficult or impossible
to implement in Erlang. Most of the BIFs belong
to the module
The most commonly used BIFs belonging to
Examples:
1> tuple_size({a,b,c}). 3 2> atom_to_list('Erlang'). "Erlang"
Notice that it is normally the set of auto-imported BIFs that are referred to when talking about 'BIFs'.