gpt4 book ai didi

prolog - 在 Prolog 中生成整数的最佳方法

转载 作者:行者123 更新时间:2023-12-02 09:38:08 25 4
gpt4 key购买 nike

我想生成整数,并且正在寻找实现此目的的最佳方法。示例:

?- number2(N).
N = 0;
N = 1;
N = 2;
...
(and so on)

现在我只是使用length/2:

number2(N) :- length(_, N).

但我认为应该有一些更好的方法(无需创建临时列表)。我可能可以根据 length/2 的代码自己编写一些代码,但我正在寻找采用现有内置谓词的解决方案。是否有比 length/2 更好的内置谓词?我找不到类似的东西。

最佳答案

很难超越你的解决方案;也许这不值得付出努力。毕竟,现在有三种建议,但在某些情况下都是不正确的:

?- time( (number2_gk(N), N == 10000) ). % your original
% 20,002 inferences, 0.007 CPU in 0.007 seconds (99% CPU, 3006132 Lips)
N = 10000

?- time( (number2_cc(N), N == 10000) ). % quadratic overhead
% 50,025,001 inferences, 28.073 CPU in 28.196 seconds (100% CPU, 1781945 Lips)
N = 10000

?- time( (next_integer(N), N == 10000) ).
% 20,002 inferences, 0.011 CPU in 0.011 seconds (100% CPU, 1822247 Lips)
N = 10000

但是,number2_cc(-1)next_integer(-1)只是循环,length/2实际上应该产生域错误,像 SICStus and many other systems做。

如您所见,CC 的解决方案比您原来的解决方案更糟糕。

mat 的建议在以下情况下也会产生不同的行为:

goal_expansion(length(Ls,L), between(0,infinite,L)) :-
var_property(Ls, fresh(true)).

as(N) :-
length(L,N),
phrase(a, L).

a --> [a], a.
a --> [].

目标 as(N) 现在循环,而不是枚举所有 N

如果您确实坚持改进,请考虑以下使用library(clpfd)的尾递归解决方案:

nat(N) :-
nat(N, 0).

nat(N, N0) :-
N #>= N0,
( N = N0
; N1 is N0+1,
nat(N, N1)
).

?- time( (nat(N), N == 10000) ).
% 1,850,152 inferences, 0.544 CPU in 0.545 seconds (100% CPU, 3399793 Lips)

这只是对如下查询的改进。否则只是浪费资源。

?- N in 1..2, nat(N).

关于prolog - 在 Prolog 中生成整数的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33063693/

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