recursionprologtail-recursionaccumulator

Prolog Accumulators. Are they really a "different" concept?


I am learning Prolog under my Artificial Intelligence Lab, from the source Learn Prolog Now!.

In the 5th Chapter we come to learn about Accumulators. And as an example, these two code snippets are given. To Find the Length of a List

without accumulators:

len([],0).
len([_|T],N) :- len(T,X), N is X+1.

with accumulators:

accLen([_|T],A,L) :- Anew is A+1, accLen(T,Anew,L).
accLen([],A,A).

I am unable to understand, how the two snippets are conceptually different? What exactly an accumulator is doing different? And what are the benefits?

Accumulators sound like intermediate variables. (Correct me if I am wrong.) And I had already used them in my programs up till now, so is it really that big a concept?


Solution

  • accumulators are intermediate variables, and are an important (read basic) topic in Prolog because allow reversing the information flow of some fundamental algorithm, with important consequences for the efficiency of the program.

    Take reversing a list as example

    nrev([],[]).
    nrev([H|T], R) :- nrev(T, S), append(S, [H], R).
    
    rev(L, R) :- rev(L, [], R).
    rev([], R, R).
    rev([H|T], C, R) :- rev(T, [H|C], R).
    

    nrev/2 (naive reverse) it's O(N^2), where N is list length, while rev/2 it's O(N).