Friday 25 September 2009

recursive and iterative

   1: sum([H|T]) -> H + sum(T);
   2: sum([]) -> 0.

1 + sum(2,3)
1 + 2 + sum(3)
1 + 2 + 3 + sum()
6
   1: sum(L) -> sum(L,0).
   2:  
   3: sum([H|T],Accumulator) -> sum(T,Accumulator + H);
   4: sum([],Accumulator) -> Accumulator.

sum([2,3], 1)
sum([3], 3)
sum([], 6)
6

Using the accumulator means you can pass state to the next call rather than having to keep all your state hanging around while you progress.

No comments: