lunedì 15 settembre 2008

15/09/2008: Erlang

Today I'm continuing my Friday work on Erlang. Sorry for not posting about that, but we had some network problems and I forgot to update during the weekend.

Here is some sample code to explain TAIL RECURSION in Erlang.

-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 basic problem we face is the sum of the integers in a list. In this code you can see two functions:

- 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