Why does Prolog generate additional variables while querying?

Viewed 71

Knowledge base:

child(martha,charlotte).
child(charlotte,caroline).
child(caroline,laura).
child(laura,rose).


descend(X,Y) :- child(X,Y).
descend(X,Y) :- child(X,Z),
                descend(Z,Y).

Query: descend(martha, laura).

Prolog first calls child(martha, laura) which fails and then returns to descend(martha, laura).

Now, it needs to call child(martha, Z) to check the conditions but why does it need to give Z to another variable like _2978? I think it would have been fine to just call (or query) child(martha, Z).

Trace:

   Call: (8) descend(martha, laura) ? creep
   Call: (9) child(martha, laura) ? creep
   Fail: (9) child(martha, laura) ? creep
   Redo: (8) descend(martha, laura) ? creep
   Call: (9) child(martha, _2978) ? creep   % HERE, why does Prolog 
                                            % need this extra variable                                             
                                            % _2978 instead of 
                                            % utilizing the original Z variable? 
   Exit: (9) child(martha, charlotte) ? creep

A simpler example: I have the knowledge base: numeral(0)

Then I query numeral(X). During the trace I can see that the first call is to numeral(_3233).

1 Answers

Internally Prolog engine doesn’t use variable names, variables are just addresses of special kind cells in memory. So when it needs to represent a term during tracing it has to reconstruct its textual representation, and as there is no names it generates them in a unified way for all variables just by numbering them in an ascending order. You might ask why it doesn’t preserve names as metadata — the answer is that it can do that but it doesn’t make a sense since due to possible recursion it will need create a ‘copy’ of same var and again we come to necessity of generic naming.

Related