gpt4 book ai didi

prolog - 如何在所有参数模式的后继算术中实现阶乘序列?

转载 作者:行者123 更新时间:2023-12-04 13:07:10 26 4
gpt4 key购买 nike

以下 Prolog 程序定义了一个谓词 fact/2 用于计算后继算术中整数的阶乘:

fact(0, s(0)).
fact(s(X), Y) :-
fact(X, Z),
prod(s(X), Z, Y).

prod(0, _, 0).
prod(s(U), V, W) :-
sum(V, X, W),
prod(V, U, X).

sum(0, Y, Y).
sum(s(X), Y, s(Z)) :-
sum(X, Y, Z).

它适用于这种参数模式下的查询:

?- fact(s(0), s(0)).
true
; false.

它也适用于这种参数模式下的查询:

?- fact(s(0), Y).
Y = s(0)
; false.

它也适用于这种参数模式下的查询:

?- fact(X, Y).
X = 0, Y = s(0)
; X = Y, Y = s(0)
; X = Y, Y = s(s(0))
; X = s(s(s(0))), Y = s(s(s(s(s(s(0))))))
; …

但是在这种参数模式下它会耗尽资源:

?- fact(X, s(0)).
X = 0
; X = s(0)
;
Stack limit (0.2Gb) exceeded
Stack sizes: local: 4Kb, global: 0.2Gb, trail: 0Kb
Stack depth: 2,503,730, last-call: 100%, Choice points: 13
In:
[2,503,730] sum('<garbage_collected>', _1328, _1330)
[38] prod('<garbage_collected>', <compound s/1>, '<garbage_collected>')
[33] fact('<garbage_collected>', <compound s/1>)
[32] fact('<garbage_collected>', <compound s/1>)
[31] swish_trace:swish_call('<garbage_collected>')

如何在所有参数模式的后继算术中实现阶乘序列?

最佳答案

第一个问题一定是为什么? 有助于理解问题:

fact(0, s(0)) :- false.fact(s(X), Y) :- fact(X, Z), false, prod(s(X), Z, Y).

This fragment alone terminates only if the first argument is given. If it is not, then there is no way to prevent non-termination, as Y is not restricted in any way in the visible part. So we have to change that part. A simple way is to observe that the second argument continually increases. In fact it grows quite fast, but for the sake of termination, one is enough:

fact2(N, F) :-
fact2(N, F, F).

fact2(0, s(0), _).
fact2(s(X), Y, s(B)) :- fact2(X, Z, B), prod(s(X), Z, Y).

而且,我应该补充一下,这甚至可以是 proved .

fact2(A,B)terminates_if b(A);b(B).
% optimal. loops found: [fact2(s(_),s(_))]. NTI took 0ms,73i,73i

但是,有一个警告......

如果只知道 F,程序现在将需要与 |F| 成正比的时间空间!这不是感叹号而是阶乘符号...

关于prolog - 如何在所有参数模式的后继算术中实现阶乘序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68850347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com