9.logic Programming and Prolog
9.logic Programming and Prolog
Lecture 9
Logic programming and Prolog
8-12-2022
Logic programming
Program in imperative languages (C++, Java, …) is
a description of sequence of instructions to be
executed one-by-one by a target machine to solve the
given problem.
The description of the problem is implicitly incorporated in
this instruction sequence, where usually it is not possible to
clearly distinguish between the description (i.e., logic) of the
problem, and the method (i.e., control) used for its solution.
In logic programming language, the description of the
problem and the method for its solution are explicitly
separated from each other.
Logic programming
Algorithm = Logic + Control
what how
Logical operators <, >, =<, >=, =:= (equal), =\= (not equal)
X =:= Y (X and Y are equal)
Built-in predicates that have side effects (e.g., input and
output )
read(N).
write(‘Hello’).
Queries in Prolog are written after a question mark ?-
?- owns(adam, book).
Prolog (cont.)
Queries in Prolog are written after a question mark ?-
for example:
?- owns(adam, book).
This query is asking Does Adam own the book?, or Is it a fact that Adam
owns the book? (If we interpret adam to be a person called Adam, and
book to be some particular book).
When a question is asked of a Prolog system, it will search through the
database. It looks for facts that unify with the fact in the question.
If Prolog finds a fact that unifies with the question, Prolog system will
respond true.
If no such fact exists in the database, Prolog system will respond false.
Prolog (cont.)
The statement p(X, 2, 2) = p (1, Y, X), succeeded if
the terms p(X, 2, 2) and p(1, Y, X) can be matched:
?- p(X, 2, 2) = p (1, Y, X).
false (Why?)
?- write(‘Hello’), nl. (nl: new line)
Prolog Example 1
Show that Socrates is mortal using the following:
Allmen are mortal.
Socrates is a man.
The goal:
?- mortal(socrates).
true
Prolog Example 2 The notation
[E|L] denotes a
list whose first
Appending two lists to produce a third list: element is E and
append([ ], Y, Y). whose rest is L
FOL Prolog
American(x) Weapon(y) Sells(x,y,z) Hostile(z) criminal(X) :- american(X), weapon(Y), sells(X, Y, Z), hostile(Z).
Criminal(x)
owns(nono, m1).
Owns(Nono,M1) and Missile(M1 ) missile(m1 ).
Missile(x) Owns(Nono,x) Sells(West,x,Nono) sells(west,X,nono):- missile(X) , owns(nono,X).
Missile(x) Weapon(x)
weapon(X) :- missile(X).
hostile(x) :- enemy(X, america) .
Enemy(x,America) Hostile(x)
american(west).
American(West) enemy(nono,america).
Enemy(Nono,America)
Example 4
% size of a list
size([ ], 0).
size([H|T], N) :- size(T, N1), N is N1 +1.