序言中带有尾递归谓词的数字乘积
Product of numbers with tail-recursive predicate in prolog
我正在尝试在 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.
我正在尝试在 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.