retractis a built-in meta-predicate used to remove facts or rules from the Prolog database while a program is executing. It is most often used in partnership with
assert(or one of its relatives). For example, your program might have hypothesised that some fact or rule is correct, added it to the Prolog database using
assert(or one of its relatives), then your program explores the consequences of that assumption, and concludes that the fact or rule was wrong. So then the program
retracts the fact or rule.
More prosaically, you might simply have a query that runs repeatedly
during a single prolog session, discovers some new facts in each
run, but needs to get rid of them at the start of the next query.
retract can be used to clean the discovered
facts out of the database.
?- assert(likes(mary, pizza)). true. ?- likes(mary, pizza). true. ?- retract(likes(mary, pizza)). true. ?- likes(mary, pizza). false. ?- assert((happy(X) :- rich(X), famous(X))). X = _G180 true. ?- retract((happy(X) :- rich(X), famous(X))). X = _G180 true.
Don't worry about the
X = _G180, that's just SWI
Prolog renaming the variable
X with a unique
name so it doesn't get confused with the (different) variable
X that you might have used in some other rule.
Note also the extra pair of parentheses
the rule, as opposed to the fact.
What a call to
retract actually does is to remove the
first fact or rule that matches the argument to
retract. If you want to remove, say, all the facts
likes with two arguments, it looks as
though you might have to call
retractall is here! This meta-predicate,
as its name suggests, retracts all facts or rules that
match its single argument. For example:
?- assert(likes(mary, pizza)), assert(likes(john, beer)). true. ?- listing(likes). :- dynamic likes/2. likes(mary, pizza). likes(john, beer).
:- dynamic/2" tells us that
is a built-in predicate that can be modified during program execution
This is to stop the program modifying unauthorised parts of
itself, and becoming totally un-debuggable. Example continues:
?- retractall(likes(X, Y)). X = _G180 Y = _G181 ?- listing(likes). :- dynamic likes/2. true.
assert. Programs that
retractall may be
particularly difficult to debug.
Tip: In some versions of Prolog,
retractall may fail if there is nothing to
retract. This may seem reasonable (though it is probably
a bug in the particular implementation) but can get in the way of a
retractall call to make sure there are
no left-over facts/rules lying around from earlier computations.
To get around this,
assert a dummy fact of the
right type (something
likes/2 is what you are trying to get
rid of), before you call
retractall. SWI Prolog
does in fact succeed on a
retractall call with no