Function is a set of instructions, which are grouped together. These grouped instructions together perform certain task. In erlang, all the functions will return a value when they are called.
Below is an example of a function that adds two numbers
add(X, Y)-> X + Y.
This function performs an add operation with X and Y values and returns the result. Function can be used as below
add(2,5).
Function declarations can consist of multiple clauses, separated by a semicolon. The Arguments in each of these clauses are evaluated by pattern matching. The following function will return 'tuple' if the Argument is a tuple in the Form: {test, X} where X can be any value. It will return 'list', if the Argument is a list of the length 2 in the form ["test", X], and It will return '{error, "Reason"}' in any other case:
function({test, X}) -> tuple;
function(["test", X]) -> list;
function(_) -> {error, "Reason"}.
If the argument is not a tuple, the second clause will be evaluated. If the argument is not a list, the third clause will be evaluated.
Function declarations can consist of so called 'Guards' or 'Guard Sequences'. These Guards are expressions that limit the evaluation of a function. A function with Guards is only executed, when all Guard Expressions yield a true value. Multiple Guards can be seperated by a semicolon.
function_name(Argument) when Guard1; Guard2; ... GuardN -> (...).
The function 'function_name' will only be evaluated, when the Guard Sequence is true. The follwing function will return true only if the argument X
is in the proper range (0..15):
in_range(X) when X>=0; X<16 -> true;
in_range(_) -> false.