Google News
logo
Prolog - Interview Questions
Explain the difference between the predicates assert/1 and retract/1 in Prolog.
In Prolog, the predicates `assert/1` and `retract/1` are used to modify the dynamic database of predicates during runtime. However, they have different purposes and behaviors. Here's the difference between `assert/1` and `retract/1`:

1. `assert/1` Predicate :
   * The `assert/1` predicate is used to dynamically add new clauses or facts to a dynamic predicate during program execution.
   * It takes a single argument, which is the clause or fact to be added to the dynamic predicate.
   * The new clause is added to the end of the dynamic predicate's definition.
   * If the dynamic predicate does not exist, `assert/1` creates it automatically.
   * Example:
     assert(parent(john, mary)).​

     This adds the fact `parent(john, mary)` to the dynamic predicate `parent/2`.
2. `retract/1` Predicate :
   * The `retract/1` predicate is used to dynamically remove specific clauses or facts from a dynamic predicate during program execution.
   * It takes a single argument, which is the clause or fact to be removed from the dynamic predicate.
   * `retract/1` only removes the first matching clause that unifies with the given argument.
   * After removal, backtracking may occur to explore other possible solutions.
   * Example:
     retract(parent(john, mary)).​

     This removes the fact `parent(john, mary)` from the dynamic predicate `parent/2`.

It's important to note that both `assert/1` and `retract/1` operate on dynamic predicates, which are explicitly declared using the `dynamic/1` directive. Attempting to use `assert/1` or `retract/1` on static predicates or undefined predicates will result in an error.

The combination of `assert/1` and `retract/1` provides the ability to dynamically modify the database of facts and rules during program execution, enabling dynamic updates and customization of the knowledge base. However, caution should be exercised when using these predicates to ensure proper synchronization and maintain consistency in the program's logic.
Advertisement