swi-prolog 中的算术表达式 [英] Arithmetic expression in swi-prolog
问题描述
我有以下序言程序:
set_1(2).
p(X) :- set_1(X+1).
我正在使用适用于 i386 的 SWI-Prolog 5.10.4 版在此程序上运行查询 p(1).
I'm using SWI-Prolog version 5.10.4 for i386 to run the query p(1) on this program.
答案是错误".
我希望答案是真",因为 set_1(X+1) 应该以 set_1(2) 为基础并用第一个事实解决.
I expect the answer to be 'true', because set_1(X+1) should be grounded as set_1(2) and resolved with the first fact.
为什么答案是错误的,我怎样才能得到真实"?
Why the answer is false and how can I get 'true' ?
推荐答案
如果您希望 X+1
在您的示例中与 2 统一,您需要使用 is 进行编码/2
.
If you want X+1
to unify with 2 in your example, you'll need to code this using is/2
.
本身 X+1
是一个有效的 Prolog 术语,但即使 X
与 1
统一,术语也变成了 1+1
,而不是您期望的 2
.
By itself X+1
is a valid Prolog term, but even when X
is unified with 1
, the term becomes 1+1
, not the 2
you expected.
尝试:
p(X) :- Y is X+1, set_1(Y).
补充:可能值得指出的是,Prolog 在计算算术表达式方面的极端懒惰"允许我们将计算责任从 p/1
推到 set_1/1
,代价是必须使谓词成为规则而不是简单的事实.
Added: It's probably worth pointing out that the extreme "laziness" of Prolog in evaluating arithmetic expressions allows us to push down responsibility for evaluation from p/1
into set_1/1
, at the expense of having to make that predicate a rule rather than a simple fact.
1 ?- [user].
|: set_1(X) :- 2 is X.
|: p(X) :- set_1(X+1).
|: {Ctrl-D}
% user://1 compiled 0.00 sec, 3 clauses
true.
2 ?- p(1).
true.
谓词 is/2
并不是唯一强制算术表达式求值的 SWI-Prolog 内置函数.请参阅此处了解完整的概要.特别是谓词 =:=
(使用中缀表示法),比较两个表达式是否具有相同的评估,在某些情况下可能很有用.
Predicate is/2
is not the only SWI-Prolog built-in that compels arithmetic expression evaluation. See here for a complete rundown. In particular predicate =:=
(with infix notation), comparing whether two expressions have equal evaluations, might be useful in some cases.
这篇关于swi-prolog 中的算术表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!