【问题标题】:Product of numbers with tail-recursive predicate in prologprolog中带有尾递归谓词的数字的乘积
【发布时间】:2017-12-09 09:08:06
【问题描述】:

我正在尝试在 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.

【问题讨论】:

    标签: prolog product tail-recursion


    【解决方案1】:

    你可以写这样的东西

    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)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多