简体   繁体   English

将数字与Prolog变量分开

[英]Separating numbers from a Prolog Variable

If I were to initialize something like this on the terminal: 如果我要在终端上初始化这样的内容:

    numbers((2,5)).

How can I obtain the two values individually. 如何分别获得两个值。 I have this on my code: 我的代码中有这个:

    numbers(Pair_numbers) :- Pair_numbers is (X, Y).

and this doesn't work. 这是行不通的。 I want the X to work as the 2 and Y as the 5 so that later on I can use them in things like: 我希望X可以用作2Y用作5以便以后可以在诸如此类的东西中使用它们:

    nth1(X, Random_list, List_Row)
    nth1(Y, List_Row, Value)

The only idiomatic option for keeping "constants" in your Prolog code is to have them as facts, as pointed out in the comment by lurker above. 如上面lurker在注释中所指出的,在Prolog代码中保留“常量”的唯一惯用方法是将它们作为事实。 You would probably have this fact somewhere in your code: 您可能在代码中的某个地方有这个事实

numbers(2, 5).

And then, when you need it, you need to evaluate the fact to get the values: 然后,在需要时,您需要评估事实以获取值:

?- numbers(X, Y), /* do something with X and Y */

This would be roughly the same idea as writing somewhere at the top of your C file: 这与在C文件顶部的某处写入大致相同的想法:

#define NUMBER1 2
#define NUMBER2 5

or maybe, in the global scope, 也许在全球范围内

const int n1 = 2;
const int n2 = 5;

As pointed out, you don't need to make it a "tuple", or any kind of other structure, just use two arguments. 正如所指出的,您无需使其成为“元组”或任何其他结构,只需使用两个参数即可。

If you want to do it from the "terminal", or rather from the top level, you might try: 如果要从“终端”,或者从顶层开始,则可以尝试:

?- assertz(numbers(2, 5)).

... but beware: you might want to make sure that you don't have this already. ...但是要当心:您可能要确保您还没有这个。 So maybe a bit safer would be: 因此,也许更安全一些:

?- retractall(numbers(_,_)), assertz(numbers(2, 5)).

or maybe 或者可能

?- abolish(numbers/2), assertz(numbers(2, 5)).

Whether you use abolish or retractall .... Read the documentation. 无论您使用abolish还是retractall ...,请阅读文档。 It depends. 这取决于。

You can also have different flavors of "global variables", but those are not worth the trouble for most use cases. 您也可以使用不同类型的“全局变量”,但是对于大多数用例而言,这些都不值得。

And one last thing: at least with SWI-Prolog, there is a trick to access the values of variables from earlier queries by using $Variable_name . 最后一件事:至少使用SWI-Prolog,有一个技巧,可以使用$Variable_name访问早期查询中的$Variable_name Here is the actual transcript from my interaction with the top level in SWI-Prolog: 这是我与SWI-Prolog中高层互动的实际成绩单:

?- X = 2.
X = 2.

?- Y = 5.
Y = 5.

?- X < Y.
ERROR: </2: Arguments are not sufficiently instantiated
?- $X < $Y.
true.

?- Z is $X + $Y.
Z = 7.

Maybe other implementations have something similar. 也许其他实现也有类似的东西。 Don't get used to it. 不习惯。

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

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