How to create global variable in prolog

FriedRike picture FriedRike · May 18, 2012 · Viewed 15.3k times · Source

I have a list that I create as follows:

tab([(top,left),(top,middle),(top,right),(center,left),(center,middle),
     (center,right),(bottom,left),(bottom,middle),(bottom,right)]).

I wish to create a global variable AllPosition that is a tab. So I did the following:

tab(AllPos).

Is this right?

Then I have to follow problem: I have a function that receives one of the pair in tab. That I wish to remove. So I did this:

place(Line, Column, Tab) :-
AllPos \== [_,_] /*while AllPos isn't empty - not sur if this is done this way*/ -> (member((Line,Column), AllPos) -> (erase(AllPos, (Line,Column), AllPos)).

where erase(List, Element, NewList) erases the element Element from List and creates a new list NewList equal to List but without Element. Both functions member and erase are working.

The thing is... As you might have noticed I use AllPoseverywhere. That's because I want to, I want to modify it so I can use it later (after having removed some elements from it), in another function. Is my logic right? Will I be able to use modified AllPos in another function? Thanks

Answer

Yeti picture Yeti · Dec 19, 2012

In SWI-Prolog you can use: b_setval(name, value) and b_getval(name, value). And in case you don't want the values change back in case of backtracking, you can make them actual global by using: nb_setval(name, value) and nb_getval(name, value).

Thus for example if you have a program and you want to check how often it went through a certain path, you can use:

recursive(100).
recursive(X) :- add, Y is X + 1, recursive(Y).

add :- nb_getval(counter, C), CNew is C + 1, nb_setval(counter, CNew).

testRecursion
:-
    % Set counter to zero
    nb_setval(counter, 0),

    % Run some code with 'add'
    recursive(0), !,

    % Print the results
    nb_getval(counter, CounterValue),
    write('Steps: '), writeln(CounterValue).

This is good for some experimental cases, but in general you will want to avoid global variables in Prolog because Prolog means programming in logic.