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

标签 math error-handling compiler-errors prolog instantiation-error

为什么该程序在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).

首先,我必须删除代码行:-sure_loaded(p31)。否则标记一个错误,指出该错误不存在。

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

错误:参数没有被充分实例化

为什么?

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

谢谢。

最佳答案

观察到goldbach/2是要定义的谓词,它使用辅助谓词goldbach/3。当满足goldbach/3上的某些条件时,goldbach/2会调用N,以便使用double作为L的辅助参数P的初始值来计算doubleton 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指令正在查找将在此开发中定义此谓词的文件。

关于math - 为什么这个哥德巴赫猜想程序在Prolog中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51226552/

相关文章:

java - 错误 : unchecked call to DefaultComboBoxModel(E[])

python - Python Kivy : pos_hint = (x.x, x.x) -> Error

Java 无法识别直线方程程序中的字符串 "-1"。查看 "equation"操作命令

asp.net-mvc - NerdDinner Visual Web Developer 2010设置

node.js - 如何在全局错误处理程序中捕获特定路由器请求的错误之前将其终止

angularjs - 在 promise 链的末尾捕捉错误

javascript - 根据三 Angular 形获取屏幕坐标

math - float 学坏了吗?

java - 将 Math.sin(x) 的结果转换为 java 中度数的结果

c# - 编译内容项目时出错