NightmaresCoding
NightmaresCoding

Reputation: 131

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:

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

Upvotes: 0

Views: 59

Answers (1)

user1812457
user1812457

Reputation:

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. 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:

#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. 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. Here is the actual transcript from my interaction with the top level in 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.

Upvotes: 2

Related Questions