prolog中带尾部递归谓词的数乘积
我试图在Prolog中编写一个尾部递归谓词:prolog中带尾部递归谓词的数乘积,prolog,product,tail-recursion,Prolog,Product,Tail Recursion,我试图在Prolog中编写一个尾部递归谓词:product(a,B),如果B是列表a中的数字的乘积,则为true。以下是我迄今为止编写的代码: 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(a,B)
,如果B
是列表a
中的数字的乘积,则为true。以下是我迄今为止编写的代码:
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.
太多了!是尾部递归吗?是的。我编辑我的答案。查看(使用trace/0)与另一个非尾部递归代码的区别