为什么这个哥德巴赫猜想程序在 Prolog 中不起作用?

Why this Goldbach's conjecture program does not work in Prolog?

为什么这个程序在 Prolog 中不起作用?

%  Goldbach's conjecture. 
% Goldbach's conjecture says that every positive even number greater 
% than 2 is the sum of two prime numbers. Example: 28 = 5 + 23.

:- ensure_loaded(p31).

% goldbach(N,L) :- L is the list of the two prime numbers that
%    sum up to the given N (which must be even).
%    (integer,integer) (+,-)

goldbach(4,[2,2]) :- !.
goldbach(N,L) :- N mod 2 =:= 0, N > 4, goldbach(N,L,3).

goldbach(N,[P,Q],P) :- Q is N - P, is_prime(Q), !.
goldbach(N,L,P) :- P < N, next_prime(P,P1), goldbach(N,L,P1).

next_prime(P,P1) :- P1 is P + 2, is_prime(P1), !.
next_prime(P,P1) :- P2 is P + 2, next_prime(P2,P1).

首先,我必须删除代码行:- ensure_loaded(p31)。否则标记为不存在的错误。

其次,当我在 SWI-Prolog 屏幕上使用 ?-goldbach(4,X,Y) 运行 时。标记了一个错误:

错误:参数未充分实例化

为什么?

有人可以帮我修复程序吗?

谢谢。

观察goldbach/2是被定义的谓词,它使用了一个辅助谓词goldbach/3goldbach/3N 上的某些条件满足时由 goldbach/2 调用以计算双例 L,使用 3 作为辅助参数 [=16= 的初始值] goldbach/3.

事实上,您可以看到 goldbach/3 将始终在实例化其第一个和第三个参数的情况下被调用。对第一个参数的要求在goldbach/2的文档中有明确说明,标记为+;当 goldbach/2 调用它的助手 goldbach/3 来执行计算时提供第三个参数。

goldbach(4, X, Y) 这样的调用失败,因为它试图执行涉及未实例化变量的算术 (Q is N - P),这会导致错误:逻辑变量的算术对 Prolog 没有意义。澄清一下,该程序应该可以正常工作,但您不应该直接调用 goldbach/3

就目前而言,缺少谓词 is_prime/1。您删除的 ensure_loaded/1 指令正在寻找定义此谓词的文件(在此开发中)。