next up previous
Next: Compound Terms Up: No Title Previous: Prolog Syntax

Scope of a variable

Within a clause, all occurrences of an identical variable refer to the same value.

For instance :

fly(X) :- green(X), dragon(X).

and happy(X) :- pass_exam(X,Y).

here, X in fly(X) and happy(X) are not related.

However, the occurrance of X in the definition of fly(X) refer to the same thing.

Also, note the change in arity of the clause happy(X).

There are some exceptions however for such anonymous variables :

balanced_child(X) :-
brother(X,_),
sister(X,_).

Here, the variable represented by _ refers to different people

and would be represented internally as :

balanced_child(X) :-
brother(X,_483),
sister(X,_485).

The advanced Trace mechanism can be used to show internal variable names

Consider the program :

check_number(0). 

check_number(N) :-
	N < 0,
	N1 is N+2,
	check_number(N1).

check_number(N) :-
	N > 0,
	N1 is N-2,
	check_number(N1).

What happens when we give the queries :

check_number(4)
check_number(100)
check_number(15)
check_number(125)

Query :

Q : check_number(4)
A : yes

I<>The program goes into a loop, nothing appears to be happening on the screen. The loop will only stop until there is no more memory left for evaluation. Hence, the program will have to be interrupted.

What can we do to prevent this happening ?

check_number(1).

Q : check_number(15)
A : yes

the new information also has to be added at a specific point, because of the way evaluation is performed by Prolog



Omer F Rana
Fri Jan 31 13:13:38 GMT 1997