11.3 Variable scoping rule
When we say "variable", we mean one of two things:
In Prolog, it is not the case that every occurrence of the same variable name necessarily refers to the same memory storage location.
For example, consider the following example program:
old(Timothy). old(Elizabeth). wise(Peter). wise(Lydia). happy(X) :- old(X). happy(X) :- wise(X).
This example program is available in the AAU directory as Old-wise.plgCG.
The program says that Timothy and Elizabeth are old, and that Peter and Lydia are wise, and that you are happy if you are either old or wise.
The program doesn't do anything useful, but it illustrates what we are talking about.
There are four occurrences of the variable name "X". Do they all refer to the same variable memory location? If not, which belong together?
The scoping rule
The scoping rule for variables in Prolog is this:
The scoping rule applied
In the example above, there are four uses of the variable name "X". We now know that the two clauses using the variable "X" could have been rewritten as:
happy(X) :- old(X). happy(Y) :- wise(Y).
without affecting the meaning. We see that the "X" referred to in the following clause:
happy(X) :- old(X).
is not the same as the "X" referred to in the other clause:
happy(X) :- wise(X).
However, within each of these clauses, the "X" does refer to the same memory location.
When we say "variable", we either refer to a variable name or to the memory location where the variable's value is stored.
Two uses of the same variable name refer to the same memory location only if the uses occur within the same clause.
Next, we present a technique for solving a programming problem which is common when programming in Prolog.
PrevLite: 11.2 Terminology
NextLite: 11.5 Quiz: Rules
Prev: 11.2 Terminology
Up: 11 Rules
Next: 11.4 Returning values from rules (Ad)