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.