在 Prolog 中实例化参数

Instantiate arguments in Prolog

考虑具有流模型 (i,o) 的 PROLOG 谓词 f(list,integer)。

f([],0).
f([H|T],S):-
    f(T,S1),
    S1 is S-H.

给出评价结果f([1,2,3,4,5,6,7,8],S)?证明答案。

我看到我们收到错误“参数未充分实例化”,这是因为 S 的值最终没有更新(仅当列表为空时)。这是一个很好的理由吗?

I've seen that we get the error "Arguments are not sufficiently instantied" and that is because the value of S is not updated in the end(only when the list is empty). Is this a good justification?

如果此代码应该失败,是的。

正确的写法是:

此谓词在第二个位置上使用 未绑定变量 调用,在顶部或递归 vai f(T,S1) (其中 S1 是新鲜的,因此未绑定)。

然后算术求值

S1 is S-H.

将在 is/2 的右侧有一个未绑定的变量并且无法继续(即它会抛出)。

但请注意,如果您切换到“有限域上的约束满足”,它会起作用:

?- use_module(library(clpfd)).
true.

然后将 is/2 替换为 #=:

f([],0).
f([H|T],S):-
    f(T,S1),
    S1 #= S-H.

产生一个工作程序:

?-  f([1,2,3,4,5,6,7,8],S).
S = 36.