asserta(X)
adds the clause X
to the front of the knowledge base. assertz(X)
adds the clause X
to the end of the knowledge base. X
must be suitably instantiated that the predicate of the clause can be determined.
This is not undone as part of backtracking.
Examples
?- X=p(1), asserta(X), asserta(p(2)), asserta(p(3)).
X = p(1)
yes
?- p(X).
X = 3
yes;
X = 2
yes;
X = 1
yes
?- retract(p(X)).
X = 3
yes;
X = 2
yes;
X = 1
yes
?- p(X).
no
?- X=p(1), assertz(X), assertz(p(2)), assertz(p(3)).
X = p(1)
yes
?- p(X).
X = 1
yes;
X = 2
yes;
X = 3
yes
?- retract(p(X)).
X = 1
yes;
X = 2
yes;
X = 3
yes
?- p(X).
no
Note: "assert" is a synonym for "assertz".
?- z(X).
no
?- assert(z(a)), assert(z(b)), assert(z(c)).
yes
?- z(X).
X = a
yes;
X = b
yes;
X = c
yes
rules can be asserted, but have to be surrounded by brackets
?- q(X,Y,Z).
no
?- assert((q(X,Y,Z) :- Z is X+Y)).
X = UNINSTANTIATED VARIABLE
Y = UNINSTANTIATED VARIABLE
Z = UNINSTANTIATED VARIABLE
yes
?- assert((q(X,Y,Z) :- Z is X-Y)).
X = UNINSTANTIATED VARIABLE
Y = UNINSTANTIATED VARIABLE
Z = UNINSTANTIATED VARIABLE
yes
?- assert((q(X,Y,Z) :- Z is X*Y, repeat(3))).
X = UNINSTANTIATED VARIABLE
Y = UNINSTANTIATED VARIABLE
Z = UNINSTANTIATED VARIABLE
yes
?- assert((q(X,Y,Z) :- Z is -X)).
X = UNINSTANTIATED VARIABLE
Y = UNINSTANTIATED VARIABLE
Z = UNINSTANTIATED VARIABLE
yes
?- q(6,3,9).
yes;
no
?- q(6,3,18).
yes;
yes;
yes;
no
?- q(6,3,17).
no
?- q(5,2,Q).
Q = 7
yes;
Q = 3
yes;
Q = 10
yes;
Q = 10
yes;
Q = 10
yes;
Q = -5
yes
?- q(6,7,Q).
Q = 13
yes;
Q = -1
yes;
Q = 42
yes;
Q = 42
yes;
Q = 42
yes;
Q = -6
yes
?- q(8,4,32).
yes;
yes;
yes;
no
?- asserta((q(X,Y,Z) :- Z is Y-X)).
X = UNINSTANTIATED VARIABLE
Y = UNINSTANTIATED VARIABLE
Z = UNINSTANTIATED VARIABLE
yes
?- q(5,2,Q).
Q = -3
yes;
Q = 7
yes;
Q = 3
yes;
Q = 10
yes;
Q = 10
yes;
Q = 10
yes;
Q = -5
yes
Argument must be suitably instantiated that the predicate of the clause can be determined.
?- asserta(X).
Expected an atom or a predicate but got a VARIABLE with value: X
?- assertz(X).
Expected an atom or a predicate but got a VARIABLE with value: X
?- asserta((p :- 7)).
Expected an atom or a predicate but got a INTEGER with value: 7
?- assertz(9).
Expected an atom or a predicate but got a INTEGER with value: 9
?- asserta(true).
Cannot replace already defined built-in predicate: true/0
?- assertz(is(1,2)).
Cannot replace already defined built-in predicate: is/2
non_dynamic_predicate(1,2,3).
?- asserta(non_dynamic_predicate(4,5,6)).
Cannot add clause to already defined user defined predicate as it is not dynamic: non_dynamic_predicate/3 clause: non_dynamic_predicate(4, 5, 6)
?- assertz(non_dynamic_predicate(4,5,6)).
Cannot add clause to already defined user defined predicate as it is not dynamic: non_dynamic_predicate/3 clause: non_dynamic_predicate(4, 5, 6)