Introduction
PROgramming in LOGic
Emphasis on what rather than how
Problem in Declarative Form
Logic Machine
Basic Machine
Prolog’s strong and weak
points
Assists thinking in terms of objects and
entities
Not good for number crunching
Useful applications of Prolog in
Expert Systems (Knowledge Representation
and Inferencing)
Natural Language Processing
Relational Databases
What is Prolog?
Prolog is the most widely used language to
have been inspired by logic programming
research. Some features:
Prolog uses logical variables. These are not
the same as variables in other languages.
Programmers can use them as ‘holes’ in
data structures that are gradually filled in
as computation proceeds.
…More
Unification is a built-in term-manipulation
method that passes parameters, returns
results, selects and constructs data
structures.
Basic control flow model is backtracking.
Program clauses and data have the same
form.
The relational form of procedures makes it
possible to define ‘reversible’ procedures.
…More
Clauses provide a convenient way to
express case analysis and
nondeterminism.
Sometimes it is necessary to use control
features that are not part of ‘logic’.
A Prolog program can also be seen as a
relational database containing rules as
well as facts.
What a program looks like
/* At the Zoo */
elephant(george).
elephant(mary).
panda(chi_chi).
panda(ming_ming).
dangerous(X) :- big_teeth(X).
dangerous(X) :- venomous(X).
guess(X, tiger) :- stripey(X), big_teeth(X), isaCat(X).
guess(X, koala) :- arboreal(X), sleepy(X).
guess(X, zebra) :- stripey(X), isaHorse(X).
Prolog is a ‘declarative’
language
Clauses are statements about what is true about
a problem, instead of instructions how to
accomplish the solution.
The Prolog system uses the clauses to work out
how to accomplish the solution by searching
through the space of possible solutions.
Not all problems have pure declarative
specifications. Sometimes extralogical
statements are needed.
Example: Concatenate lists a
and b list procedure cat(list a, list b)
{
In an imperative language list t = list u = copylist(a);
while (t.tail != nil) t = t.tail;
t.tail = b;
return u;
}
cat(a,b)
In a functional language if b = nil then a
else cons(head(a), cat(tail(a),b))
cat([], Z, Z).
In a declarative language cat([H|T], L, [H|Z]) :- cat(T, L, Z).
Complete Syntax of Terms
Term
Constant Compound Term Variable
Names an individual Names an individual Stands for an individual
that has parts unable to be named when
program is written
Atom Number likes(john, mary) X
alpha17 0 book(dickens, Z, cricket) Gross_pay
gross_pay 1 f(x) Diagnosis
john_smith 57 [1, 3, g(a), 7, 9] _257
dyspepsia 1.618 -(+(15, 17), t) _
+ 2.04e-27 15 + 17 - t John
=/= -13.6
’12Q&A’
Compound Terms
The parents of Spot are Fido and Rover.
parents(spot, fido, rover)
Functor (an atom) of arity 3. components (any terms)
It is possible to depict the term as a tree:
parents
spot fido rover
Examples of operator properties
Position Operator Syntax Normal Syntax
Prefix: -2 -(2)
Infix: 5+17 +(17,5)
Postfix: N! !(N)
Associativity: left, right, none.
X+Y+Z is parsed as (X+Y)+Z These are all the
because addition is left-associative. same as the
normal rules of
Precedence: an integer.
arithmetic.
X+Y*Z is parsed as X+(Y*Z)
because multiplication has higher precedence.
The last point about
Compound Terms…
Constants are simply compound terms of arity 0.
badger
means the same as
badger()
Structure of Programs
Programs consist of procedures.
Procedures consist of clauses.
Each clause is a fact or a rule.
Programs are executed by posing queries.
An example…
Example
Predicate
Procedure for elephant
Facts
elephant(george).
Clauses elephant(mary).
elephant(X) :- grey(X), mammal(X), hasTrunk(X).
Rule
Example
?- elephant(george).
Queries
yes
?- elephant(jane).
Replies
no
Clauses: Facts ‘if’and Rules
‘provided that’
‘turnstile’
Head :- Body. This is a rule.
Head. This is a fact.
Full stop at the end.
Body of a (rule) clause contains
goals.
Head Body
likes(mary, X) :- human(X), honest(X).
Goals
Exercise: Identify all the parts of Prolog
text you have seen so far.
Interpretation of Clauses
Clauses can be given a declarative reading or a
procedural reading.
Form of clause: H :- G1, G2, …, Gn.
Declarative reading: “That H is provable follows from
goals G1, G2, …, Gn being provable.”
Procedural reading: “To execute procedure H, the
procedures called by goals G1, G2,
…, Gn are executed first.”
?- pair(percival, X).
?- pair(apollo, daphne).
male(bertram). ?- pair(camilla, X).
male(percival). ?- pair(X, lucinda).
?- pair(X, X).
female(lucinda). ?- pair(bertram, lucinda).
female(camilla). ?- pair(X, daphne).
?- pair(X, Y).
pair(X, Y) :- male(X), female(Y).
Worksheet 2
drinks(john, martini). ?- pair(X, john, martini).
drinks(mary, gin). ?- pair(mary, susan, gin).
drinks(susan, vodka). ?- pair(john, mary, gin).
drinks(john, gin). ?- pair(john, john, gin).
drinks(fred, gin). ?- pair(X, Y, gin).
?- pair(bertram, lucinda).
?- pair(bertram, lucinda, vodka).
pair(X, Y, Z) :-
?- pair(X, Y, Z).
drinks(X, Z),
drinks(Y, Z).
This definition forces X and Y to be distinct:
pair(X, Y, Z) :- drinks(X, Z), drinks(Y, Z), X \== Y.
Worksheet
(a) Representing a3symmetric relation.
(b) Implementing a strange ticket condition.
berkshire surrey
kent
wiltshire hampshire sussex
How to represent this relation?
Note that borders are symmetric.
WS3
This relation represents
What about the other?
one ‘direction’ of border:
(a) Say border(kent, sussex).
border(sussex, kent).
border(sussex, kent).
border(sussex, surrey).
border(surrey, kent).
border(hampshire, sussex).
(b) Say
border(hampshire, surrey).
adjacent(X, Y) :- border(X, Y).
border(hampshire, berkshire). adjacent(X, Y) :- border(Y, X).
border(berkshire, surrey).
border(wiltshire, hampshire).
border(wiltshire, berkshire). (c) Say
border(X, Y) :- border(Y, X).
WS3
Now a somewhat strange type of discount ticket. For the
ticket to be valid, one must pass through an intermediate
county.
A valid ticket between a start and end county obeys the
following rule:
valid(X, Y) :- adjacent(X, Z), adjacent(Z, Y)
WS3
border(sussex, kent).
valid(X, Y) :-
border(sussex, surrey).
adjacent(X, Z),
border(surrey, kent).
border(hampshire, sussex). adjacent(Z, Y)
border(hampshire, surrey).
border(hampshire, berkshire).
border(berkshire, surrey).
border(wiltshire, hampshire). ?- valid(wiltshire, sussex).
border(wiltshire, berkshire). ?- valid(wiltshire, kent).
?- valid(hampshire, hampshire).
adjacent(X, Y) :- border(X, Y). ?- valid(X, kent).
adjacent(X, Y) :- border(Y, X). ?- valid(sussex, X).
?- valid(X, Y).
A Typical Prolog program
Compute_length ([],0).
Compute_length ([Head|Tail], Length):-
Compute_length (Tail,Tail_length),
Length is Tail_length+1.
High level explanation:
The length of a list is 1 plus the length of the tail
of the list, obtained by removing the first
element of the list.
This is a declarative description of the
computation.
Fundamentals
(absolute basics for writing Prolog
Programs)
Facts
John likes Mary
like(john,mary)
Names of relationship and objects must begin
with a lower-case letter.
Relationship is written first (typically the
predicate of the sentence).
Objects are written separated by commas and
are enclosed by a pair of round brackets.
The full stop character ‘.’ must come at the
end of a fact.
More facts
Predicate Interpretation
valuable(gold) Gold is valuable.
owns(john,gold) John owns gold.
father(john,mary) John is the father of
Mary
gives (john,book,mary) John gives the book to
Mary
Questions
Questions based on facts
Answered by matching
Two facts match if their predicates are same
(spelt the same way) and the arguments each
are same.
If matched, prolog answers yes, else no.
No does not mean falsity.
Prolog does theorem proving
When a question is asked, prolog tries
to match transitively.
When no match is found, answer is no.
This means not provable from the given
facts.
Variables
Always begin with a capital letter
?- likes (john,X).
?- likes (john, Something).
But not
?- likes (john,something)
Example of usage of variable
Facts:
likes(john,flowers).
likes(john,mary).
likes(paul,mary).
Question:
?- likes(john,X)
Answer:
X=flowers and wait
;
mary
;
no
Conjunctions
Use ‘,’ and pronounce it as and.
Example
Facts:
likes(mary,food).
likes(mary,tea).
likes(john,tea).
likes(john,mary)
?-
likes(mary,X),likes(john,X).
Meaning is anything liked by Mary also liked by John?
Backtracking (an inherent property
of prolog programming)
likes(mary,X),likes(john,X)
likes(mary,food)
likes(mary,tea)
likes(john,tea)
likes(john,mary)
1. First goal succeeds. X=food
2. Satisfy likes(john,food)
Backtracking (continued)
Returning to a marked place and trying to resatisfy is
called Backtracking
likes(mary,X),likes(john,X)
likes(mary,food)
likes(mary,tea)
likes(john,tea)
likes(john,mary)
1. Second goal fails
2. Return to marked place
and try to resatisfy the first goal
Backtracking (continued)
likes(mary,X),likes(john,X)
likes(mary,food)
likes(mary,tea)
likes(john,tea)
likes(john,mary)
1. First goal succeeds again, X=tea
2. Attempt to satisfy the likes(john,tea)
Backtracking (continued)
likes(mary,X),likes(john,X)
likes(mary,food)
likes(mary,tea)
likes(john,tea)
likes(john,mary)
1. Second goal also suceeds
2. Prolog notifies success and waits for a reply
Rules
Statements about objects and their relationships
Expess
If-then conditions
I use an umbrella if there is a rain
use(i, umbrella) :- occur(rain).
Generalizations
All men are mortal
mortal(X) :- man(X).
Definitions
An animal is a bird if it has feathers
bird(X) :- animal(X), has_feather(X).
Syntax
<head> :- <body>
Read ‘:-’ as ‘if’.
E.G.
likes(john,X) :- likes(X,cricket).
“John likes X if X likes cricket”.
i.e., “John likes anyone who likes cricket”.
Rules always end with ‘.’.
Another Example
sister_of (X,Y):- female (X),
parents (X, M, F),
parents (Y, M, F).
X is a sister of Y is
X is a female and
X and Y have same parents
Question Answering in presence
of rules
Facts
male (ram).
male (shyam).
female (sita).
female (gita).
parents (shyam, gita, ram).
parents (sita, gita, ram).
Question Answering: Y/N type: is sita the
sister of shyam?
?- sister_of (sita, shyam)
parents(sita,M,F) parents(shyam,M,F)
female(sita)
parents(shyam,gita,ram)
parents(sita,gita,ram)
success
Question Answering: wh-type: whose
sister is sita?
?- ?- sister_of (sita, X)
parents(sita,M,F) parents(Y,M,F)
female(sita)
parents(Y,gita,ram)
parents(sita,gita,ram)
parents(shyam,gita,ram)
Success
Y=shyam
Exercise
1. From the above it is possible for
somebody to be her own sister. How
can this be prevented?
An example Prolog Program
Rules
Statements about objects and their relationships
Expess
If-then conditions
I use an umbrella if there is a rain
use(i, umbrella) :- occur(rain).
Generalizations
All men are mortal
mortal(X) :- man(X).
Definitions
An animal is a bird if it has feathers
bird(X) :- animal(X), has_feather(X).
Prolog Program Flow,
BackTracking and Cut
Controlling the program flow
Prolog’s computation
Depth First Search
Pursues a goal till the end
Conditional AND; falsity of any
goal prevents satisfaction of
further clauses.
Conditional OR; satisfaction of any
goal prevents further clauses being
evaluated.
Control flow (top level)
Given
g:- a, b, c. (1)
g:- d, e, f; g. (2)
If prolog cannot satisfy (1), control will
automatically fall through to (2).
Control Flow within a rule
Taking (1),
g:- a, b, c.
If a succeeds, prolog will try to satisfy b,
succeding which c will be tried.
For ANDed clauses, control flows forward
till the ‘.’, iff the current clause is true.
For ORed clauses, control flows forward till
the ‘.’, iff the current clause evaluates to
false.
What happens on failure
REDO the immediately preceding
goal.
Fundamental Principle of prolog
programming
Always place the more general rule
AFTER a specific rule.
CUT
Cut tells the system that
IF YOU HAVE COME THIS FAR
DO NOT BACKTRACK
EVEN IF YOU FAIL SUBSEQUENTLY.
‘CUT’ WRITTEN AS ‘!’ ALWAYS SUCCEEDS.
Fail
This predicate always fails.
Cut and Fail combination is used to
produce negation.
Since the LHS of the neck cannot
contain any operator, A ~B is
implemented as
B :- A, !, Fail.
Predicate Calculus
Introduction through an example (Zohar Manna,
1974):
Problem: A, B and C belong to the Himalayan
club. Every member in the club is either a
mountain climber or a skier or both. A likes
whatever B dislikes and dislikes whatever B likes.
A likes rain and snow. No mountain climber likes
rain. Every skier likes snow. Is there a member
who is a mountain climber and not a skier?
Given knowledge has:
Facts
Rules
A wrong prolog program!
1. member(a).
2. member(b).
3. member(c).
4. mc(X);sk(X) :- member(X) /* X is a mountain climber or skier or
both if X is a member; operators NOT allowed in the head of a
horn clause; hence wrong*/
5. like(X, snow) :- sk(X). /*all skiers like snow*/
6. \+like(X, rain) :- mc(X). /*no mountain climber likes rain; \+ is
the not operator; negation by failure; wrong clause*/
7. \+like(a, X) :- like(b,X). /* a dislikes whatever b likes*/
8. like(a, X) :- \+like(b,X). /* a dislikes whatever b likes*/
9. like(a,rain).
10. like(a,snow).
?- member(X),mc(X),\+sk(X).
Prolog’s way of making and
breaking a list
Problem: to remove duplicates from a list
rem_dup([],[]).
rem_dup([H|T],L) :- member(H,T), !, rem_dup(T,L).
rem_dup([H|T],[H|L1]) :- rem_dup(T,L1).
Note: The cut ! in the second clause needed, since after
succeeding at member(H,T), the 3rd clause should
not be tried even if rem_dup(T,L) fails, which prolog
will otherwise do.
List Syntax
Samples:
[mia, vincent, jules, yolanda]
[mia, robber(honey_bunny), X, 2, mia]
[]
[mia, [vincent, jules], [butch,
girlfriend(butch)]]
[[], dead(z), [2, [b, c]], [], Z, [2, [b, c]]]
List Syntax
Enclose lists in brackets
Any type elements
Empty list is []
Lists can contain lists
All lists have an implied empty list at
the end
Head and Tail
• Use [ H | T ] to extract the first element:
[Head|Tail] = [mia, vincent, jules, yolanda].
Head = mia
Tail = [vincent,jules,yolanda]
• Multiple elements:
[H1, H2 |Tail] = [mia, vincent, jules, yolanda].
H1 = mia
H2 = vincent
Tail = [ jules,yolanda]
• No more elements:
[H1 |Tail] = [mia].
H1 = mia
Tail = [ ]
• Empy list has no Head and Tail
Are you a member of a list?
• Either X is the head
• Or x is a member of the tail
• Remember the empty list has no Head and Tail
so the empty tail wont fit member(X,[X|T]).
• member(X,[X|T]).
member(X,[H|T]) :- member(X,T).
• Because you don't care about H in second or T
in first, replace with _
• member(X,[X|_]).
member(X,[_|T]) :- member(X,T).