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