Modifying the Database at Runtime
Prolog's clause database is not immutable: assert/1 (and its directional variants asserta/1 and assertz/1) add new facts or rules while the program runs, and retract/1 and retractall/1 remove them, letting a program change its own behavior mid-execution. Any predicate targeted this way must first be declared with :- dynamic Name/Arity, so the compiler doesn't treat calls to a predicate with no static clauses as an error; this single directive is what turns a plain predicate into one Prolog expects to be modified at runtime.
Cricket analogy: It's like a chief selector who can add a player to the national squad mid-series after an injury replacement, rather than working from a fixed team sheet locked before the tournament — dynamic/1 declares which 'squads' (predicates) are allowed to be edited on the fly like this.
assertz/1 and asserta/1: Adding Clauses
assertz(Clause) appends Clause to the end of the existing clauses for that predicate, so it will be tried last during backtracking, while asserta(Clause) inserts it at the front, so it's tried first; both accept either a plain fact like counter(0) or a full rule like discount(Item, 10) :- premium_member(Item). This ordering control is what lets you implement simple priority schemes — for instance, asserta/1 to push a just-computed cache entry to the front so it's found before slower fallback clauses.
Cricket analogy: It's like adding a new batter to the very end of the batting order with assertz/1 versus promoting a pinch-hitter straight to the top with asserta/1 — both put a new 'clause' (player) into the lineup, but the order in which they're tried during the innings (backtracking) differs completely.
:- dynamic(cache/2).
fib_memo(N, F) :-
cache(N, F), !.
fib_memo(0, 0) :- !, assertz(cache(0, 0)).
fib_memo(1, 1) :- !, assertz(cache(1, 1)).
fib_memo(N, F) :-
N1 is N - 1, N2 is N - 2,
fib_memo(N1, F1),
fib_memo(N2, F2),
F is F1 + F2,
assertz(cache(N, F)).
?- fib_memo(30, F).
F = 832040.
?- retractall(cache(_, _)). % clear the memoization cache
true.retract/1 and retractall/1: Removing Clauses
retract(Clause) removes the first clause in the database that unifies with Clause, and if Clause's head is bound but its body is left as a variable, it will only match facts (bodies of true); retractall(Head) is more aggressive, removing every clause whose head matches Head regardless of body, and — unlike retract/1 — it succeeds even if no clauses matched, making it the safer choice for 'clear everything about this' operations such as resetting a cache. A common beginner mistake is expecting retract/1 to remove multiple matching clauses on a single call; it removes exactly one per call and must be wrapped in a failure-driven loop or replaced with retractall/1 to clear several at once.
Cricket analogy: It's like a scorer correcting a single wrongly-recorded delivery from the ball-by-ball log with retract/1, versus wiping the entire over's record clean with retractall/1 if the whole over needs to be redone — one removes exactly one entry, the other clears every matching entry at once.
assert/1 and retract/1 are side effects that take place immediately and are never undone by backtracking. A goal that asserts a fact and then fails will leave that fact in the database — this is a common source of subtle bugs when developers assume Prolog's usual 'undo everything on failure' behavior applies to the database itself.
The Logical Update View and Practical Patterns
Because assert and retract take effect immediately and are not undone on backtracking — Prolog's logical update view specifies that a goal already running sees the set of clauses that existed when it started, while new invocations see the current state — assert/retract are genuine side effects, closer to imperative mutation than to logical inference, and should be used deliberately for tasks like memoizing expensive computations, maintaining simulation state, or building a runtime fact base from parsed input, rather than as a substitute for proper recursive logic.
Cricket analogy: It's like a DRS review that, once confirmed, stands regardless of whether the umpire later reconsiders the over — an assert made mid-query persists even if the query itself later backtracks, because the change to the 'match record' isn't undone the way normal move choices are.
- Predicates modified at runtime must first be declared with :- dynamic Name/Arity.
- assertz/1 appends a clause to the end of a predicate's clause list; asserta/1 inserts it at the front.
- retract/1 removes exactly one matching clause per call; use a failure-driven loop or retractall/1 to remove several.
- retractall/1 removes every clause whose head matches, regardless of body, and succeeds even with zero matches.
- assert/retract take effect immediately and are never undone by backtracking, unlike ordinary variable bindings.
- The logical update view means a goal already executing sees the clause set as it was when the goal started.
- assert/retract are best reserved for genuine state — memoization, caches, simulations — not as a substitute for recursive logic.
Practice what you learned
1. What must be done before a predicate can be safely asserted to or retracted from?
2. What is the difference between asserta/1 and assertz/1?
3. What happens when retract/1 is called on a predicate with three clauses that all unify with the given pattern?
4. Are the effects of assert/1 and retract/1 undone if the enclosing goal later backtracks or fails?
5. Which predicate is the safer choice for clearing every fact about a predicate, even if none currently exist?
Was this page helpful?
You May Also Like
findall, bagof, and setof
The three built-in all-solutions predicates that collect every proof of a goal into a list, each with different rules for failure, grouping, and duplicates.
Higher-Order Predicates in Prolog
How Prolog treats goals as ordinary data, enabling call/N, maplist, foldl, include, exclude, and partition to parameterize control flow.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics