$=

Meta-programming

As in its famous predecessor Lisp, in Prolog programs may be treated as data. To this end Prolog offers a number of so-called meta-predicates that allow to inspect and manipulate terms and clauses. An example of a meta-predicate is the one-argument predicate var that may be used to check whether a term is a variable. A quite powerful facility is offered by the meta-predicate clause. A goal of the form
clause(A,B) may be used to select all clauses of which the head unifies with A and the body with B. When both A and B are variables the goal clause(A,B) results in enumerating all clauses, binding A to the head and B to the body of the clause currently pointed at. For clauses that represent facts, B will be bound to true.

A naive meta-interpreter

\prologindex{meta-interpreter} \prologindex{backward chaining} An interesting application of meta-programming is a simple (meta) interpreter for Prolog written in only a few lines of Prolog. \pprog{backward}{
   backward(true).
   backward((A,B)) :-
  	backward(A),
  	backward(B).
   backward(A) :-
  	clause(A,B),
  	backward(B).
  
} The case analysis performed by the interpreter is straightforward. The goal true succeeds immediately. A conjunctive goal is split into parts which are successively evaluated. An atomic goal is solved by looking for a clause of which the head matches the goal, and solving the body of that clause. The interpreter described above implements a so-called backward chaining inference procedure that is strongly analogous to the inference procedure of Prolog. The procedure described here does not, however, take account of cuts. A meta-interpreter of this kind is an excellent starting point for implementing an expert system since it is rather easy to adapt the inference procedure to particular cases or to extend it with explanation facilities, certainty-factors or a consultation component.\ftn{ A similar backward chaining interpreter will be used in the distributed medical expert system described in chapter 4. } C.f.  [Sterling].