Archive for April 5, 2011

Introduciton to Erlang : Recursion (2/2)

This entry is part 10 of 16 in the series Introduction to Erlang

Accumulators

In several cases, as with the mlists:length/1 example, the non-tail recursive function can be easily turned to a tail recursive one by using the notion of accumulator. An accumulator is an extra argument introduced to a function in order to aggregate the partial results of the function. It turns the “bottom-up” collection of the final result to “top-down”.

In order to add and initialize the accumulator argument one has to introduce an extra function definition.

tlr(...) ->
    tlr(..., Accumulator_initial_value).
 
% the clause that "breaks" the recursion and
% returns the result
tlr(..., Accumulator) -> 
    Accumulator;
tlr(..., Accumulator) ->
    ...,
    Accumulator_new_value = ...,
    ...,
    trl(..., Accumulator_new_value).

Notice that typically you would only export the tlr/1 function and the tlr/2 would remain for inner-module use and not visible to the module’s users.
Read the rest of this entry »