Erlang -- Functions

Erlang Reference Manual

User's Guide

Version 10.1

- User's Guide
- PDF
- Top

- Expand All
- Contract All

### Chapters

- Introduction
  - Top of chapter
  - Purpose
  - Prerequisites
  - Document Conventions
  - Complete List of BIFs
  - Reserved Words
- Character Set and Source File Encoding
  - Top of chapter
  - Character Set
  - Source File Encoding
- Data Types
  - Top of chapter
  - Terms
  - Number
  - Atom
  - Bit Strings and Binaries
  - Reference
  - Fun
  - Port Identifier
  - Pid
  - Tuple
  - Map
  - List
  - String
  - Record
  - Boolean
  - Escape Sequences
  - Type Conversions
- Pattern Matching
  - Top of chapter
  - Pattern Matching
- Modules
  - Top of chapter
  - Module Syntax
  - Module Attributes
  - Comments
  - module_info/0 and module_info/1 functions
- Functions
  - Top of chapter
  - Function Declaration Syntax
  - Function Evaluation
  - Tail recursion
  - Built-In Functions (BIFs)
- Types and Function Specifications
  - Top of chapter
  - The Erlang Type Language
  - Types and their Syntax
  - Type Declarations of User-Defined Types
  - Type Information in Record Declarations
  - Specifications for Functions
- Expressions
  - Top of chapter
  - Expression Evaluation
  - Terms
  - Variables
  - Patterns
  - Match
  - Function Calls
  - If
  - Case
  - Send
  - Receive
  - Term Comparisons
  - Arithmetic Expressions
  - Boolean Expressions
  - Short-Circuit Expressions
  - List Operations
  - Map Expressions
  - Bit Syntax Expressions
  - Fun Expressions
  - Catch and Throw
  - Try
  - Parenthesized Expressions
  - Block Expressions
  - List Comprehensions
  - Bit String Comprehensions
  - Guard Sequences
  - Operator Precedence
- Preprocessor
  - Top of chapter
  - File Inclusion
  - Defining and Using Macros
  - Predefined Macros
  - Macros Overloading
  - Flow Control in Macros
  - -error() and -warning() directives
  - Stringifying Macro Arguments
- Records
  - Top of chapter
  - Defining Records
  - Creating Records
  - Accessing Record Fields
  - Updating Records
  - Records in Guards
  - Records in Patterns
  - Nested Records
  - Internal Representation of Records
- Errors and Error Handling
  - Top of chapter
  - Terminology
  - Exceptions
  - Handling of Run-time Errors in Erlang
  - Exit Reasons
- Processes
  - Top of chapter
  - Processes
  - Process Creation
  - Registered Processes
  - Process Termination
  - Message Sending
  - Links
  - Error Handling
  - Monitors
  - Process Dictionary
- Distributed Erlang
  - Top of chapter
  - Distributed Erlang System
  - Nodes
  - Node Connections
  - epmd
  - Hidden Nodes
  - C Nodes
  - Security
  - Distribution BIFs
  - Distribution Command-Line Flags
  - Distribution Modules
- Compilation and Code Loading
  - Top of chapter
  - Compilation
  - Code Loading
  - Code Replacement
  - Running a Function When a Module is Loaded
- Ports and Port Drivers
  - Top of chapter
  - Ports
  - Port Drivers
  - Port BIFs

# 6 Functions

### 6.1 Function Declaration Syntax

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 when:

    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 N is the arity of the function. A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions.

A function named f in the module m and with arity N is often denoted as m:f/N.

A clause body consists of a sequence of expressions separated by comma (,):

    Expr1,
    ...,
    ExprN

Valid Erlang expressions and guard sequences are described in Expressions.

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

### 6.2 Function Evaluation

When a function m:f/N is called, first the code for the function is located. If the function cannot be found, an undef runtime error occurs. Notice that the function must be exported to be visible outside the module it is defined in.

If the function is found, the function clauses are scanned sequentially until a clause is found that fulfills both of the following two conditions:

- The patterns in the clause head can be successfully matched against the given arguments.
- The guard sequence, if any, is true.

If such a clause cannot be found, a function_clause runtime error occurs.

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 fact:

    -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 is matched against argument 1. The matching succeeds and the guard (N>0) is true, thus N is bound to 1, and the corresponding body is evaluated:

    N * fact(N-1) => (N is bound to 1)
    1 * fact(0)

Now, fact(0) is called, and the function clauses are scanned sequentially again. First, the pattern N is matched against 0. The matching succeeds, but the guard (N>0) is false. Second, the pattern 0 is matched against 0. The matching succeeds and the body is evaluated:

    1 * fact(0) =>
    1 * 1 =>
    1

Evaluation has succeed and m:fact(1) returns 1.

If m:fact/1 is called with a negative number as argument, no clause head matches. A function_clause runtime error occurs.

### 6.3 Tail recursion

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 fact(N-1).

### 6.4 Built-In Functions (BIFs)

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 erlang but there are also BIFs belonging to a few other modules, for example lists and ets.

The most commonly used BIFs belonging to erlang(3) are auto-imported. They do not need to be prefixed with the module name. Which BIFs that are auto-imported is specified in the erlang(3) module in ERTS. For example, standard-type conversion BIFs like atom_to_list and BIFs allowed in guards can be called without specifying the module name.

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