1
votes

I'm trying to write a tail-recursive predicate in Prolog: product(A,B), which is true if B is the product of the numbers in list A. Here is the code I've written so far:

product(A, B) :- product(A, 1, B).
product(0, B, B) :- !.
product(A, X, B) :- Z is A - 1, Y is X * A, product(Z, Y, B).

The code works without a list. I'm pretty new to lists in Prolog, so I want to ask what is the best way to do this. The query should be something like this:

?- product([1,2,3], B).
B = 6.
1

1 Answers

1
votes

You can write something like that

product(In, Out) :-
    % We call the predicate product/3, initialize with 1 
    product(In, 1, Out).

% when the list is empty with have the result
product([], Out, Out).

% we compute the first element of the list
product([H|T], Cur, Out) :-
    Next is Cur * H,
    % we carry on with the rest
    product(T, Next, Out).

EDIT Product not tail recursive.

product1([], 1).

product1([H|T],Out) :-
    product1(T, Next),
    Out is Next * H.