Erlang Tail Recursion

Erlang Variables

A function is called tail recursive when the recursive call to itself happens only in the last expression of the body in every clause.

Syntax:

1
2
3
4
5
6
7
8
non_tail_recursive(...) ->
  non_tail_recursive(...),
  other_expression,
  ... .
tail_recursive(...) ->
  other_expression,
  ...
  tail_recursive(...).

The first function is not the tail recursive as the recursive call is followed by other expression. While the second is, since the recursive call is the last statement.

Tail Recursion & Performance
In many programming languages tails recursion is a good approach performance. But in general, it is not the case in the latest releases of Erlang. Tail recursion is not guaranteed to give you better performance.

Tail Recursion VS Non Tail Recursion

Non Tail Recursive:

1
2
length([]) -> 0;
length([_ | T]) -> 1 + length(T).

Tail Recursive:

1
2
3
4
length(List) -> length(List, 0).

length([], L) -> L;
length([_ | T], L) -> length(T, L + 1).