$= Dynamic program modification Another powerful feature that Prolog offers is the facility to assert or retract clauses dynamically. Asserting a clause results in adding the clause to the program. Retracting a clause effects the removal of that clause. A example of the use of asserting clauses dynamically is given by the simple forward chaining inference procedure defined below. C.f. [Su85]. \prologindex{dynamic modification} \prologindex{\it assert} \pprog{forward}{ forward(G) :- G. forward(G) :- clause(A,B), B, assert(A), forward(G). } Forward chaining halts when the condition kept in the argument G of forward is satisfied. As long as the condition to stop has not been asserted, the forward chaining procedure asserts every fact that can be derived using one of the clauses. Clauses are tried irrespective of the goal that must be proved, which is reflected in the independence of the argument of forward representing the condition to halt and the variables used to select a clause. Forward chaining may be used to solve connectivity problems such as the one below. \pprog{connects}{ link(a,b). link(b,c). link(c,d). link(d,e). connects(X,Y) :- link(X,Y). connects(X,Y) :- link(X,Z), connects(Z,Y). } The goal ?- forward( connects(a,e) ). may now be used to check whether a is connected to e. A side-effect of evaluating this goal is the addition of the facts connects(a,b), connects(a,c),... Backward chaining, that may be used as well to solve this particular goal, will have no such effect.
forward(G) :- G. forward(G) :- clause(A,B), B, assert(A), forward(G).
link(a,b). link(b,c). link(c,d). link(d,e). connects(X,Y) :- link(X,Y). connects(X,Y) :- link(X,Z), connects(Z,Y).