Skip to content

Database Operations

Clausal Prolog supports runtime modification of the predicate database — adding and removing clauses while a program is running. This enables dynamic state, memoization, and self-modifying programs.

Examples on this page are Clausal Prolog (.clausal): ISO Prolog syntax, without cut. (The seam, Clausal's Python-syntax surface, writes the directive -dynamic(Name/Arity) and has a different default for undeclared names; the page notes where.)


Quick Example

:- dynamic(color/1).

color(red).
color(blue).

test("assert and query") :-
    assertz(color(green)),
    color(green).

Declare first: the dynamic/1 directive

assertz, asserta and retract modify a dynamic predicate, declared with :- dynamic(Name/Arity).. A predicate that has clauses in its module and no declaration is static once the module has loaded, as in ISO Prolog: modifying it raises permission_error(modify, static_procedure, Name/Arity), with the builtin as the culprit (Scryer's form; see Exceptions). Builtins are static too.

:- dynamic(seen/1).

stable(1).

test("a dynamic predicate accepts assertz") :-
    assertz(seen(x)),
    seen(x).

test("a static predicate refuses it") :-
    catch(assertz(stable(2)), E, true),
    E == error(permission_error(modify, static_procedure, stable/1), assertz/1).

The declaration also makes the predicate exist before it has clauses: a dynamic predicate with no clauses simply fails, where calling an undeclared name with no clauses raises existence_error(procedure, Name/Arity). Asserting into a name that does not exist at all follows the module flag assert_creates_dynamic, which is true in a .clausal module (and an imported .pl one): as in ISO 7.5.2(2), the assert creates it as a dynamic procedure. (A seam module has the flag false, so there an undeclared name is refused with the same permission_error(modify, static_procedure, Name/Arity).) Declaring the predicate is still the clear way to say it is meant to change. Declare several at once:

:- dynamic(counter/1).
:- dynamic(cache/2).

See Directives for the other directives.

From Python: Module.declare_dynamic

A Module built from Python has no directives, so declare its dynamic predicates with Module.declare_dynamic(name, arity), the same declaration as :- dynamic(name/arity).. It also works on the Module of a loaded .seam or .clausal file (mod.__clausal_module__).

from clausal import Module, Var, solve

m = Module("counter")
m.declare_dynamic("count", 1)          # :- dynamic(count/1).
list(solve(("assertz", ("count", 0)), module=m))
n = Var()
[n.value for _ in solve(("count", n), module=m)]    # [0]

It is idempotent. Its errors are ISO dynamic/1's, raised as a LogicException whose culprit is dynamic/1: instantiation_error for an unbound argument, type_error(atom, Name), type_error(integer, Arity), domain_error(not_less_than_zero, Arity), and permission_error(modify, static_procedure, Name/Arity) for a builtin or a static predicate that already has clauses.


Adding Clauses

assertz/1

assertz(Term) — add a fact at the end of the clause list (like Prolog's assertz).

:- dynamic(fact/1).

fact(init).

test("assert") :-
    assertz(fact(42)),
    fact(42).

asserta/1

asserta(Term) — add a fact at the beginning of the clause list (like Prolog's asserta). The new clause will be tried first on subsequent queries.

:- dynamic(priority/1).

priority(low).

test("assert first") :-
    asserta(priority(high)),
    priority(high).

Rules: only in a .pl module

A .pl file is ISO Prolog, so a goal running in a .pl module can assert a rule as well as a fact, as ISO 13211-1 8.9 says (operator ruling 2026-11-03):

:- dynamic(p/1).
add :- assertz((p(X) :- member(X, [1, 2, 3]), X > 1, !)), assertz(p(9)).
?- add, findall(X, p(X), L).          % L = [2]
?- clause(p(A), B).                   % B = (member(A,[1,2,3]),A>1,!)
?- retract((p(_) :- B)).              % binds B, removes the rule
  • The asserted clause is a copy of the term (ISO 8.9.1.1): binding the caller's variables afterwards does not change it, and a variable goal in the body is stored as call(G). In a .pl module this holds for an asserted fact too: after assertz(q(X)), X = 1, q(V) leaves V unbound. (A Clausal Prolog or seam fact still keeps an unbound argument the caller's variable.)
  • It is compiled as the same clause written in that file would be: the native front end's own clause lowering, under the file's directives (its imports, library(reif)'s if_/3, library(clpq)'s {}/1). So ! and -> have their ISO meaning there, fixed when the rule is asserted: a cut is local to the asserted clause whoever calls the predicate, and opaque inside \+, call/1 and findall/3. *-> is refused, as everywhere (existence_error(procedure, '*->'/2)).
  • clause/2 gives the body as written, and retract((Head :- Body)) unifies Body too; retract(Head) removes a fact only.
  • The logical update view (ISO 7.5.4): a call sees the clauses as they were when it started. A clause asserted while it runs is not seen by it, and a clause retracted meanwhile is still answered. retract/1 itself iterates the clauses as they were at its call.
  • A non-callable body is type_error(callable, Body), the whole body as culprit, as in Scryer (assertz((p :- (a, 4)))).
  • A rule holds data as deep as a fact can (tested to 20000 levels). A body whose control constructs nest too deeply to compile (a few hundred levels of ->) is error(resource_error(stack), assertz/1), raised before anything is stored.

Where a rule may not be asserted, the assert raises permission_error(assert, rule, Head) and leaves the predicate untouched:

  • in a Clausal Prolog (.clausal) or seam module, which assert facts only;
  • into a procedure of a Clausal Prolog module, even from a .pl module (the clause would be compiled in that cut-free module);
  • at the ?- top level on its default surface; it is allowed with --prolog, or when the top level has loaded a .pl file.

A Clausal Prolog module cannot call an asserted rule any more than a consulted one: it never calls into a .pl module (permission_error(access, prolog_module, M)).

Asserting a rule costs more than asserting a fact (it is lowered and compiled to Python, roughly 0.35 ms against 0.05 ms), and the predicate is recompiled once, at its next call, as for facts.


Removing Clauses

retract/1

retract(Term) — remove the first clause whose head unifies with Term.

:- dynamic(item/1).

item(a).
item(b).
item(c).

test("retract") :-
    retract(item(b)),
    findall(I, item(I), ITEMS),
    ITEMS == [a, c].

As in ISO (8.9.3) and Scryer, retract of a name nothing declares simply fails — there is no clause to remove — while a static predicate, a declared data functor or a builtin raises error(permission_error(modify, static_procedure, Name/Arity), retract/1), and an unbound Term raises instantiation_error. retractall(Head) (ISO 8.9.5) removes every clause whose head unifies with Head and always succeeds; abolish(Name/Arity) (ISO 8.9.4) removes a dynamic procedure altogether, so a later call is an existence_error.

retract uses unification for matching, so you can retract by pattern:

:- dynamic(pair/2).

pair(x, 1).
pair(y, 2).
pair(z, 3).

test("retract by pattern") :-
    retract(pair(y, _)),
    findall(K-V, pair(K, V), PAIRS),
    PAIRS == [x-1, z-3].

Table Management

abolish_table/2

abolish_table(functor, Arity) — clear cached answers for a specific tabled predicate.

:- table(memo_fib/2).

memo_fib(0, 0).
memo_fib(1, 1).

test("clear") :-
    abolish_table(memo_fib, 2).

abolish_all_tables/0

abolish_all_tables — clear all tabling caches at once.

test("clear all") :-
    abolish_all_tables.

Patterns & Recipes

Memoization

Cache computed results in a dynamic predicate. Arithmetic goes through CLP(ℤ) constraints (N1 #= N - 1); ISO N1 is N - 1 would also do here, since N is bound. (In the seam, a bare X is N - 1 is unification and would bind X to the unevaluated term; see Operators.)

:- use_module(library(clpz)).
:- dynamic(fib_cache/2).

% Look in the cache once: a hit answers from it, a miss computes and stores.
fib(N, F) :-
    findall(F0, fib_cache(N, F0), CACHED),
    fib_cached(CACHED, N, F).

fib_cached([F], _, F).
fib_cached([], N, F) :-
    fib_compute(N, F),
    assertz(fib_cache(N, F)).

fib_compute(0, 0).
fib_compute(1, 1).
fib_compute(N, F) :-
    N #> 1,
    N1 #= N - 1,
    N2 #= N - 2,
    fib(N1, F1),
    fib(N2, F2),
    F #= F1 + F2.

test("memoized fib") :-
    fib(30, F),
    F == 832040,
    fib_cache(30, 832040).

(For automatic memoization, consider :- table instead.)

Counter / mutable state

:- dynamic(ctr/1).

ctr(0).

increment(NEW) :-
    retract(ctr(OLD)),
    NEW is OLD + 1,
    assertz(ctr(NEW)).

test("counter") :-
    increment(1),
    increment(2),
    ctr(2).

Collecting facts from a computation

:- dynamic(result/1).

collect_evens(LIST) :-
    in_(X, LIST),
    X mod 2 =:= 0,
    assertz(result(X)),
    fail.
collect_evens(_).

test("collect") :-
    collect_evens([1, 2, 3, 4]),
    findall(X, result(X), [2, 4]).

(Prefer findall for this pattern — it is cleaner and does not require dynamic predicates.)


Gotchas

  • A predicate with clauses must be declared dynamic — without it, assertz/asserta/retract raise error(permission_error(modify, static_procedure, Name/Arity), assertz/1) (catchable by catch/3; the culprit is matched as written, assertz/1). A name with no declaration and no clauses is created by assertz/asserta in a .clausal module, where the flag assert_creates_dynamic is on; retract of such a name just fails. (In a seam module the flag is off and the assert is refused; to match the culprit in a seam catch pattern, quote it, '/'('assertz', 1), because a bare builtin name in a seam term is the builtin's object, not the atom.)
  • A Clausal Prolog module asserts facts, not rules — assertz((foo(X) :- bar(X))) raises permission_error(assert, rule, Head) at assert time (the predicate's existing clauses are left untouched). A .pl module asserts rules too: see Rules: only in a .pl module.
  • Arity is part of the name — foo/1 and foo/2 are different predicates: declaring foo/2 dynamic says nothing about foo/1. In a .clausal module, assertz(foo(a)) then creates a new dynamic foo/1; in a seam module it is refused with error(permission_error(modify, static_procedure, foo/1), assertz/1), since an undeclared procedure is static there (ISO 7.5.2).
  • retract removes one clause — it removes the first matching clause only. Call it in a loop (or use findall + multiple retracts) to remove all matches.
  • Order matters — assertz appends, asserta prepends. The clause order affects which solution is found first.
  • Tabling interaction — if a tabled predicate depends on dynamic facts, remember to abolish_table after modifying the facts, or the cached answers will be stale.

See also: Directives — dynamic and other predicate directives, Tabling — automatic memoization with table, Meta-Predicates — findall as an alternative to assert-based collection.