序言中具有尾部回收谓词的数字的产物



我正在尝试在prolog: product(A,B)中编写一个尾部回复谓词,如果 B是列表 A中的数字的产物,则是正确的。这是我到目前为止写的代码:

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).

代码无需列表而起作用。我对Prolog中的列表非常陌生,所以我想问什么是最好的方法。查询应该是这样的:

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

您可以写类似的东西

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).

编辑产品不递归递归。

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

最新更新