Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 40 ยท Data Structures and Parsing

The Dynamic Database: assert and retract

Change a Prolog program while it runs. Learn dynamic declarations, assertz, asserta, retract, retractall, the counter and memoization patterns, and when not to use the database.

A Prolog program is a database of clauses, and that database is not frozen. Predicates declared dynamic can gain and lose clauses while the program runs, using assert and retract. This is how Prolog programs keep state: counters, caches, a to-do list, facts learned from the user. It is also the most "un-Prolog" feature of the language, because the effect of a call now depends on what happened before. This lesson shows how it works and, just as important, when to avoid it.

Declaring dynamic predicates

By default, clauses loaded from a file are static: SWI-Prolog refuses to modify them. To let a predicate change, declare it once, at the top of your file:

PROLOG
:- dynamic counter/1, visited/1.

The declaration also makes a call to a predicate with no clauses fail quietly, rather than raising an existence error. That matters for state predicates that start out empty.

Adding and removing clauses

Predicate Effect
assertz(Clause) add Clause at the end of its predicate
asserta(Clause) add Clause at the beginning
assert(Clause) same as assertz
retract(Clause) remove the first clause that unifies; backtracking removes the next ones
retractall(Head) remove every clause whose head unifies with Head
PROLOG
?- assertz(color(red)), assertz(color(blue)), asserta(color(green)).
true.

?- findall(C, color(C), L).
L = [green, red, blue].

?- retract(color(red)).
true.

?- findall(C, color(C), L).
L = [green, blue].

You can also assert rules: assertz((double(X, Y) :- Y is X * 2)). Note the extra parentheses around the clause so the :- is read as one argument. retractall(color(_)) clears a predicate and, if it was not declared yet, makes it dynamic; it is the safe way to reset state.

A subtle but important rule is the logical update view: when a goal starts to run a predicate, it sees the clauses as they were at that moment. Clauses added or removed during the call do not change the iteration already in progress. This prevents surprising infinite loops when a predicate asserts into itself.

Pattern 1: a counter

Prolog variables cannot be reassigned, so a mutable counter lives in the database. Increment it by removing the old fact and adding a new one:

PROLOG
:- dynamic counter/1.
counter(0).

increment :-
    retract(counter(N)),
    N1 is N + 1,
    assertz(counter(N1)).
PROLOG
?- increment, increment, increment, counter(X).
X = 3.

Always retract and assert in the order shown: retract binds N to the old value, which you then use. If retract fails (because the fact is missing), the whole increment fails, a good sign that your initial state is wrong.

Pattern 2: memoization

Naive recursive Fibonacci recomputes the same values exponentially many times. A cache of already-computed answers, stored as facts, fixes that:

PROLOG
:- dynamic memo/2.

fib(N, F) :- memo(N, F), !.
fib(N, F) :- N < 2, !, F = N.
fib(N, F) :-
    N1 is N - 1, N2 is N - 2,
    fib(N1, F1), fib(N2, F2),
    F is F1 + F2,
    assertz(memo(N, F)).

The first clause looks for a stored answer and cuts if found. Otherwise the value is computed and recorded for next time. This is the manual way; Tabling and Performance shows the :- table directive that does it automatically.

Try it

Prolog is not available on this site, so the program runs on a small Python stand-in engine that supports facts, rules, the cut, assertz, asserta and retract. It ignores :- dynamic lines, which a real Prolog needs.

Python Counter and memoization (Python stand-in engine)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Facts that come and go (Python stand-in engine)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading facts back, and persistence

Changes to the database live only in memory. To keep them, write the clauses to a file with listing/1 or portray_clause/1, or use the persistency library to log assertions to disk automatically. For a larger store, use a real database through the ODBC or SQLite bindings. For quick sessions, tell/told or open/3 with portray_clause/2 is enough.

Prolog also has global variables (nb_setval/2, nb_getval/2, b_setval/2). They are faster than assert for counters in tight loops, but they have the same drawback: hidden state.

When not to use the dynamic database

  • When a parameter would do. Passing state through arguments (an accumulator or a state variable) keeps predicates pure and testable. Most loops do not need assert.
  • When you can use findall or aggregate_all. Collecting results in a list is cleaner than asserting them one by one.
  • In code that backtracks. Assertions are not undone on backtracking, so a failed branch may leave stray facts. That is sometimes the point (a cache) but often a bug.
  • In reusable library code. Hidden state makes predicates impossible to reason about in isolation and unsafe with threads unless you add mutexes or use thread-local predicates (:- thread_local).

A good rule: assert for caches, for user-entered facts (an expert system learning answers, see Meta-Interpreters and Expert Systems) and for global configuration. Avoid it as a general replacement for variables.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call adds a fact at the start of a predicate?

    asserta puts the clause first, assertz puts it last.
  2. 2. What does retractall(item(_)) do?

    retractall removes every clause whose head unifies with the pattern and succeeds even if none matched.
  3. 3. Why does the counter use retract(counter(N)) and then assertz(counter(N1))?

    State lives in the database: take out the old value, put in the new one.
  4. 4. What happens to asserted facts when a later goal fails and Prolog backtracks?

    assert and retract are not undone on backtracking, which is why they need care.

Summary

  • Declare changeable predicates with :- dynamic name/arity.
  • assertz/1 and asserta/1 add clauses; retract/1 and retractall/1 remove them.
  • Counters and caches (memoization) are the classic uses; the logical update view keeps running calls stable.
  • Changes are not undone on backtracking and are lost at exit unless saved.
  • Prefer passing state through arguments; reach for assert when a cache or persistent fact is the right model.

Next: Atoms, Strings and Characters