Posts Tagged ‘recursion’
Introduciton to Erlang : Recursion (2/2)
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 »
Introduction to Erlang : Recursion (1/2)
Recursion
The definition of the word recursion is “(mathematics) an expression such that each term is generated by repeating a particular mathematical operation”, according to the WordNet. Recursion is one of the most powerful “tools” in a functional programming language and so it is for Erlang. Recursion can be used to apply divide and conquer 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’s body definition includes a call to the function itself.
functionA(...) -> Body_before_recursion, % optional functionA(...), Body_after_recursion. % optional |
Recursion is used instead of the conventional loop statements of other programming languages, such as while
and for
in C.
Read the rest of this entry »