Information Technology Reference
In-Depth Information
8.3.2 Dynamic predicates in Prolog
Section 8.3.3 deals with declarative sentences. There, instead of being used to query the
world model, a declarative sentence is used to update it. In other words, a declarative
sentence is interpreted as providing new information that needs to be incorporated into
the world model.
Prolog allows the clauses associated with some of the predicates to be changed
by a program itself. These are called dynamic predicates. For example, suppose a
predicate my_pred ( x , y , z ) takes three arguments. To make that predicate dynamic, a
special Prolog declaration dynamic is used. The line
:- dynamic my_pred/3.
is included in the program file before my_pred is used. The clauses in the file can then
define my_pred as usual, but there are also two special Prolog operations, assert and
retract , which can be used in queries or in the bodies of clauses:
assert( atom )
This query always succeeds; it has the effect of adding the atom as a clause to
Prolog's knowledge base.
retract( atom )
This query has the effect of removing the first clause in Prolog's knowledge base
that matches the atom. It fails if there is no match.
So Prolog programs can be written as follows:
get_married(X) :-
retract(single(X)), % X is no longer single.
assert(married(X)). % X is now married.
Predicates like this can be used to keep a model of a changing world up-to-date. So
for example, if a program with this predicate is loaded together with a world model
that contains the fact that John is single, the following behavior results:
?- single(john).
Yes
?- get_married(john).
Yes
?- single(john).
No
?- married(john).
Yes
 
 
Search WWH ::




Custom Search