简体   繁体   English

如何将比较结果存储在 Prolog 中并稍后使用?

[英]How do I store the result of a comparison in Prolog and use it later?

Say I want to write an (admittedly unnecessary, but it's an example) predicate that compares two values, and returns the result as a variable that can be referenced, something like this:假设我想编写一个(不可否认,但它是一个示例)谓词来比较两个值,并将结果作为可以引用的变量返回,如下所示:

compare(Value1, Value2, Result) :- 
    Result is Value1 > Value2.

But in Swish I get an error:但是在Swish 中,我收到一个错误:

src:2: Syntax error: Operator priority clash
compare/3: Domain error: `order' expected, found `'5''

After I have Result , how would I then use its value in another predicate?在获得Result之后,我将如何在另一个谓词中使用它的值? Would it be possible to say:是否可以说:

compare(5, 2, Result),
Result.

Or am I completely misunderstanding the philosophy of Prolog?还是我完全误解了 Prolog 的哲学?

Superficially, it's a problem of operators' precedence: this compiles从表面上看,这是运算符优先级的问题:这会编译

compare(Value1, Value2, R) :- R is (Value1 > Value2).

but it doesn't run:但它没有运行:

?- compare(1,3,X).
ERROR: compare/3: Type error: `atom' expected, found `1' (an integer)

You're going to clash with a builtin, see compare /3.您将与内置函数发生冲突,请参阅比较/3。 Better to avoid, although in SWI-Prolog redefine_system_predicate /1 directive could help.最好避免,尽管在 SWI-Prolog 中redefine_system_predicate /1 指令可能会有所帮助。

is /2 is a predicate implementing a small (?) functional sublanguage, evaluating right side arithmetic expression, while > /2 implements the comparison after evaluating both sides. is /2 是一个实现小 (?) 函数式子语言的谓词,评估右侧算术表达式,而> /2 实现评估两侧后的比较。 What I mean:我的意思是:

..., A > B, ...

it's either true or false, doesn't yields a number...它是对还是错,不会产生数字...

Maybe you want也许你想要

my_compare(A,B,C) :- A > B -> C = 1 ; A < B -> C = -1 ; C = 0.

edit :编辑

I think I should illustrate how to store the comparison value: just instance the result and call it later.我想我应该说明如何存储比较值:只需实例化结果并稍后调用它。

my_compare(A,B,C) :- A > B -> C = true ; C = false.

then然后

?- my_compare(1,3,R), (R -> writeln('comparison succeeded') ; writeln('comparison failed')).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM