Prolog ERROR: is/2: Arguments are not sufficiently instantiated

Prolog ERROR: is/2: Arguments are not sufficiently instantiated

我是 Prolog 的新手。我写了一个很短的程序如下:

plus(X,Y,R):- R is X+Y.

当我 运行 它时,我遇到了以下问题:

?- plus(1,1,2).
true
?- plus(1,1,X).
X=2
?- plus(1,X,2).
ERROR: is/2: Arguments are not sufficiently instantiated

为什么会出现这个错误?如何修改代码以实现相同的目标? 谢谢大家的帮助!!!

这不起作用的原因是 is/2 是(像)一个函数。给定 X,Y,它计算 X+Y 并将其存储到 R(它用 X+Y 实例化 R)。如果提供了R,而X或Y是一个var(还没有实例化)那么它怎么计算X+Y,这就是实例化错误的原因。

要解决这个问题,您应该使用更相关的模块,例如 :CLPFD

:- use_module(library(clpfd)).

plus(X,Y,R):- R #= X+Y.

一些例子:

**?- [ask].
true.
?- plus(1,1,2).
true.
?- plus(1,1,X).
X = 2.
?- plus(1,X,2).
X = 1.
?- plus(X,Y,2).
X+Y#=2.
?- plus(X,Y,R).
X+Y#=R.**

您可以在给出答案的最后一个案例中看到 X、Y 和 R 是如何相关的。