11.3 Variable scoping rule

Introduction

When we say "variable", we mean one of two things:

  1. We can mean "variable name", e.g., "X". That is, a string of characters that make up a name. This name identifies the variable (in the next sense).

  2. We can mean the memory storage location that holds the value that the variable name stands for.

In Prolog, it is not the case that every occurrence of the same variable name necessarily refers to the same memory storage location.

Example

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:

Two uses of an identical name for a variable only refer to the same memory location if they are within a single clause.

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.

Summary

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

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)