Prolog (4)
To make program modification safe, some Prolog interpreters (and compilers) ask a predicate dynamic P/N to be used to declares a predicate name P with N arguments as a "dynamic" predicate, so its definition in the database (as facts and rules) can be changed at run time. By default the built-in predicates and predicates defined in files are static, that is, cannot be modified at run time.
To call it (and any other goals) when a file of Prolog program is loading:
:- dynamic factorial/2.
The actual changes of a database is carried out by the following predicates:
The goal listing(P) will display the current definition of the predicate P in the database.
Example: the following program will add facts into the database:
:- dynamic factorial/2.
factorial(0, 1).
factorial(N, A) :- N > 0, N1 is N - 1, factorial(N1, A1), A is N*A1,
asserta(factorial(N, A)), write(' * ').
When it runs, new results will be remembered to avoid repeated calculation.
?- factorial(3, X).
* * *
X = 6
Yes
?- factorial(3, X).
X = 6
Yes
?- listing(factorial).
:- dynamic factorial/2.
factorial(3, 6).
factorial(2, 2).
factorial(1, 1).
factorial(0, 1).
factorial(A, B) :-
A>0,
C is A-1,
factorial(C, D),
B is A*D,
asserta(factorial(A, B)),
write(' * ').
Yes
Operator "univ", written as "=..", converts between a term and a list, such as
p(X, Y) =.. [p, X, Y]. It is useful for modifying dynamic predicates.
An example to form a fact:
?- X =.. [bird, tweety], assert(X). X = bird(tweety) Yes ?- bird(Y). Y = tweety ; No
Predicate clause(H,B) retrieves rules in memory whose head matches H and body matches B. H must be sufficiently instantiated to determine the main predicate of the head. Example:
?- clause(append([a], [b], [a, b]), X). X = append([], [b], [b]) Yes
After a goal P has been built, it can be invoked by call(P). The goal succeed if P does, else fail. Example:
?- X =.. [append, [a], [b], Y], call(X). X = append([a], [b], [a, b]) Y = [a, b] YesIn this way, a program can be built in run time, then executed.
The predicate call is also used in other places, such as to define negation.
Constraints on a problem are represented by propositions, including equations and inequalities. Answers are found by reasoning. For example:
?- X + 2 = 7. X = 5
The major differences between the two types of languages:
| Prolog | Java/C++ |
|
|
Suitable situations:
| Prolog | Java/C++ |
|
|
See LISP Primer and Chapter 16 of the textbook.