Prolog递归程序不返回值

Prolog recursive program not returning values

我还是 Prolog 的新手,我遇到了一个我不知道如何修复的错误。 我写了一个简单的求幂程序,如下所示:

exp(b, 0, R) :- R is 1.         % non-recursive case: exponent is 0
exp(0, e, R) :- R is 0.         % non-recursive case: base is 0
exp(Base, Exponent, Result) :-  % recurse if base and exponent are non-negative
    Base >= 0,
    Exponent >= 0,
    E1 is Exponent-1,
    exp(Base, E1, R1),
    Result is Base*R1.

这编译得很好,但是当我 运行 它并给它一个查询时,比如 exp(2, 4, X)。我遇到了以下输出:

?- exp(2, 4, X).
false.

我是不是做错了什么?或者是以某种我不知道的方式格式化结果的问题?

你混淆了变量原子。如果您简单地将两个非递归子句更改为:

,它将按预期工作
exp(_, 0, 1).
exp(0, _, 0).

事实上,我建议更改整个程序以在整个过程中使用 CLP(FD) 约束

exp(_, 0, 1).
exp(0, _, 0).
exp(Base, Exponent, Result):-
    Base #>= 0,
    Exponent #>= 0,
    E1 #= Exponent-1,
    exp(Base, E1, R1),
    Result #= Base*R1.

例如,现在至少可以得出一个解决方案:

?- exp(2, X, 16).
X = 4

而我们之前有:

?- exp(2, X, 16).
>=/2: Arguments are not sufficiently instantiated

另请注意最常见的查询:

?- exp(X, Y, Z).
Y = 0,
Z = 1 ;
X = Z, Z = 0 ;
X = Z,
Y = 1,
Z in 0..sup ;
X = Z, Z = 0,
Y in 0..sup,
_G801+1#=Y,
_G801 in -1..sup .