Here is some sample code to explain TAIL RECURSION in Erlang.
The basic problem we face is the sum of the integers in a list. In this code you can see two functions:
-module(sum).
-export([
sum/1,
sum_acc_caller/1,
sum_acc/2
]).
sum([H|T]) -> H + sum(T);
sum([]) -> 0.
sum_acc([H|T], X) -> sum_acc(T, X+H);
sum_acc([], X) -> X.
sum_acc_caller(H) -> sum_acc(H, 0).
- the first one is sum/1. This is the basic, non-tail-recursive function. It calls itself (n-1) times, where n is the size of the list, and then returns the expected value.
- the second one is sum_acc/2. This is the tail-recursive function: it uses an accumulator variable X to keep the value of the sum while traversing the list. It keeps adding to this variable until the remaining part of the list (tail) has size 0; then it returns the sum.
Nessun commento:
Posta un commento