Erlang Recursion

Erlang Variables

The definition of the word Recursion is “(mathematics) an expression such that each term is generated by repeating a particular mathematical operation”. Recursion is one of the most powerful “tools” in a functional programming language.

Recursion can be used to divide techniques to problem solving, where a problem is broken to smaller subproblems, the subproblems are solved, and the results are “merged” to generate the final result.

Recursion happens when a function calls itself directly or indirectly. Recursion is used instead of the conventional loop statements of other programming languages, such as while and for in C.

Syntax:

1
2
3
4
functionA(...) ->
  Body_before_recursion, % optional
  functionA(...),
  Body_after_recursion. % optional

Example:

example.erl
1
2
3
4
5
6
7
-module(example).
-export([sum/1]).

sum(1) -> 1;
sum(N) -> N + sum_n(N - 1).

%% example:sum(10).
example.erl
1
2
3
4
5
6
7
-module(example).
-export([fac/1]).

fac(1) -> 1;
fac(N) -> N * fac(N - 1).

%% example:fac(10).
example.erl
1
2
3
4
5
6
7
-module(example).
-export([list_sum/1]).

list_sum([]) -> 0;
list_sum([H|T]) -> H + sum_list(T).

%% example:list_sum([1, 2, 3, 4, 5]).
example.erl
1
2
3
4
5
6
7
-module(example).
-export([list_increase_element/1]).

list_increase_element([]) -> [];
list_increase_element([H|T]) -> [H + 1|increase(T)].

%% example:list_increase_element([1, 2, 3, 4, 5]).
example.erl
1
2
3
4
5
6
7
-module(example).
-export([list_length/1]).

list_length([]) -> 0;
list_length([_H|T]) -> 1 + list_length(T).

%% example:list_length([1, 2, 3, 4, 5]).