Lecture 22-26 Prolog

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 57

PROLOG

PROgramming in LOGic

A Brief Introduction

---
PRO-LOG
1975, Phillippe Roussell
Predicate Calculus
Declarative Language
Predicates and Rules
Inference Mechanism
No effective standardization

---
PROLOG Paradigm
 PROgramming in LOGic
Draw inferences from facts and rules
 PROLOG is
declarative - specify facts and logical relationships
 Non-procedural: "what", not "how".
 Execute the specification.  
 Program execution as theorem proving.
 Database language with automated search and the ability to follow
general rules.
symbolic - symbols are used to represent objects
high level - contains a built-in problem solving mechanism
 PROLOG Programming
Declaring some facts about objects and their relationships
Defining some rules about objects and their relationships
Asking questions about objects and their relationships

---
PROLOG Paradigm

Prolog Database
Query
Facts + Rules

 The PROLOG Programmer


Loads facts and rules into the database.
Makes queries to the database to see if a fact is:
in the database or
can be implied from the facts and rules therein

---
System Interaction
Problem solving in PROLOG
1. insert facts and rules into the database
2. ask questions (queries) based on the contents of the
database
 Facts
Used to represent unchanging information about objects and
their relationships.
Only facts in the PROLOG database can be used for problem
solving.
Insert facts into the database by,
 typing the facts into a file and loading (consulting) the file into a
running PROLOG system

---
System Interaction
 Queries
Retrieve information from the database by entering QUERIES
A query,
 is a pattern that PROLOG is asked to match against the database
 has the syntax of a compound query
 may contain variables

A query will cause PROLOG to


 look at the database
 try to find a match for the query pattern
 execute the body of the matching head
 return an answer

---
 Logic Programming
 Logic programming is a form of declarative programming
 A program is a collection of axioms
Each axiom is a Horn clause of the form:
H :- B1, B2, ..., Bn.
where H is the head term and Bi are the body terms
Meaning H is true if all Bi are true
 A user of the program states a goal (a theorem) to be
proven
The logic programming system attempts to find axioms using
inference steps that imply the goal (theorem) is true

---
Basic Proof technique - modus ponens

A -> B
A
---------
B

---
 Resolution
 To deduce a goal (theorem), the logic programming system
searches axioms and combines sub-goals
 For example, given the axioms:
C :- A, B.
D :- C.
 To deduce goal D given that A and B are true:
Forward chaining (from fact to goal) deduces that C is true:
C :- A, B
and then that D is true:
D :- C
Backward chaining (from goal to fact) finds that D can be proven if sub-
goal C is true:
D :- C
the system then deduces that the sub-goal is C is true:
C :- A, B
Since the system could prove C it has proven D

---
Prolog Uses backward chaining
More efficient than forward chaining for larger
collections of axioms
Interactive (hybrid compiled/interpreted)
Applications: expert systems, artificial
intelligence, natural language
understanding, logical puzzles and games

---
PROLOG Paradigm
Examples (Facts)

English PROLOG

“A dog is a mammal” isa(dog, mammal).


“A sparrow is a bird” isa(sparrow, bird).

---
PROLOG Paradigm
Examples (Rules)
English PROLOG

“Something is an animal animal(X) :- isa(X,mammal).


if it is a mammal or a bird” animal(X) :- isa(X, bird).

---
PROLOG Paradigm
Examples (Queries)
English PROLOG

“is a sparrow an animal?” ?- animal(sparrow).


answer: “yes” yes
“is a table an animal?” ?- animal(table).
answer: “no” no
“what is a dog?” ?- isa(dog, X).
answer: “a mammal” X = mammal

---
PROLOG syntax
 Constants
Atoms
 Alphanumeric atoms - alphabetic character sequence starting with a
lower case letter
Examples: apple a1 apple_cart
 Quoted atoms - sequence of characters surrounded by single
quotes
Examples: ‘Apple’ ‘hello world’
 Symbolic atoms - sequence of symbolic characters
Examples: & < > * - + >>
 Special atoms
Examples: ! ; [ ] {}
Numbers
 Integers and Floating Point numbers
Examples: 0 1 9821 -10 1.3 -1.3E102

---
PROLOG syntax
 Variable Names
a sequence of alphanumeric characters beginning with
an upper case letter or an underscore
Examples: Anything _var X _

 Compound Terms (structures)


an atom followed by an argument list containing
terms. The arguments are enclosed within brackets
and separated by commas
Example: isa(dog, mammal)

---
Prolog syntax
 The names of all relationships and objects must
begin with a lower case letter. For example
studies, ali, programming
 The relationship is written first and the objects
are enclosed within parentheses and are written
separated by commas. For example studies(ali,
programming)
 The full stop character ‘.’ must come at the end
of a fact.
 Order is arbitrary but it should be consistent

---
Example
 Program with three facts and
one rule:

rainy(columbo).  ?- snowy(C).
rainy(ayubia). C = ayubia
cold(ayubia).
snowy(X) :- rainy(X), cold(X).
because rainy(ayubia) and
 Query and response: cold(ayubia) are sub-goals
?- snowy(ayubia). that are both true facts in
yes the database

 Query and response: snowy(X) with X=columbo


?- snowy(columbo). is a goal that fails, because
no cold(X) fails, triggering
backtracking
 Query and response:
?- snowy(lahore).
No
---
rainy(columbo).
rainy(ayubia).
cold(ayubia).
snowy(X) :- rainy(X), cold(X).

?- snowy(C).
C = ayubia
C = ayubia

snowy(C)
C=X C = X = ayubia
snowy(X)
AND

rainy(X) cold(X)
OR
X = columbo X = ayubia
rainy(columbo) rainy(ayubia) cold(ayubia)

---
Logic Representation :
Propositional Calculus
 Propositional Logic
Boolean statements
Logic connectives     

Example – a family
Statement Logic
p

Ahmed is not father of
Atomic statements Belal
p: Ahmed is father of Belal
q: Ahmed is brother of Aslam pq Ahmed is father of Belal or
r : Aslam is uncle of Belal Ahmed is brother of Aslam

pqr If Ahmed is father of Belal


Complex statements  and brother of Aslam then
Aslam is uncle of Belal

---
Prolog Programming
Predicate Calculus Prolog code
 Predicates Predicates
man(symbol)
man(Ahmed) father(symbol, symbol)
father(Ahmed, Belal) brother(symbol, symbol)
brother(Belal, Chand) owns(symbol, symbol)
brother(Chand, Delawar) tall(symbol)
hates(symbol, symbol)
owns(Belal, car) family()
tall(Belal) Clauses
hates(Ahmed, Chand) man(ahmed).
family() father(ahmed, belal).
brother(ahmed, chand).
 Formulae owns(belal, car).
X,Y,Z(man(X)  man(Y)  father(Z,Y)  father(Z,X) tall(belal).
 hates(ahmed, chand).
brother(X,Y)) family().
 Variables brother(X,Y):-
X, Y and Z man(X),
man(Y),
father(Z,Y),
 Constants father(Z,X).
Ahmed, Belal, Chand, Delawar and car Goal
brother(ahmed,belal).

---
Sections of Prolog Program (1-3)
 Predicates
Declarations of Relations or Rules
Just like function prototype (declaration).
Zero or more arguments
Example
Predicates
man(symbol)
family()
a_new_predicate (integer, char)

---
Sections of Prolog Program (2-3)
 Clauses
Definition(s) of Predicate = Sentence OR Phrase
Types
 Rules (function definitions)
– 0 or more conditions (statements)
 Facts
– 0 conditions
– All parameters constant
Examples
 Fact
brother(ahmed, chand).
 Rule
brother(X,Y):-
man(X),
man(Y),
father(Z,Y),
father(Z,X).

---
Sections of Prolog Program (3-3)
 Goal
Goal of inference
Only and exactly one instance
The only tentative section of the program
The main() of prolog
Goal truth value = output of program
Syntactically and Semantically just another clause
 Empty, simple (one goal), or compound (sub-goals)
Examples
 Goal
brother(X,chand). <or> brother(ahmed,chand).
 Goal
brother(X,chand),
father().

---
Sample Program Update
domains
person = symbol
predicates brother(X,Y):-
nondeterm father(person,person) X<>Y,
nondeterm brother(person,person) father(Z,X),
nondeterm cousin(person,person) father(Z,Y).
nondeterm grandfather(person,person)
cousin(X,Y):-
clauses father(A,X),
father(a,b). father(B,Y),
father(a,c). brother(A,B).
father(a,d).
father(b,e). grandfather(X,Y):-
father(b,f). father(Z,Y),
father(b,g). father(X,Z).
father(c,h). goal
father(c,i). cousin(X,Y).
father(d,j).
father(d,k).
---
Sample Program Update
A

B C D

E F G H I J K

Example Family Tree

---
Prolog Variables
 Constant placeholders (NOT variables)
Bounded once
 Loosely typed
 Start with Capital letter or underscore
 Examples
brother(ahmed, Ahmed)
brother(ahmed, _x)
Brother(ahmed, X)
 Anonymous variable
The _
Some value that isn’t required
Example
brother(ahmed, _)

---
Other Syntactic Elements
 Special predicates
cut <or> !
not(predicate)
 Predefined predicates
write(arg1[,arg2[,arg3[,arg4[…..]]]])
nl
readint(var)
readchar(var)
readln(var)
… many more related to i/o, arithmetic, OS etc

---
Other Syntactic Elements
Operators
Arithmetic
 + - * div / mod
Relational
 < <= => > = <> ><

Additional domains
Facts
Database

---
PROLOG Lists
 Lists
a sequence of terms of the form
[t1, t2, t3, t4, ..., tn]
where term ti is the ith element of the list

Examples:
[a,b,c] is a list of three elements a, b and c.

[[a,list,of,lists], and, numbers,[1,2,3]]


is a four element list.

[ ] is the ‘empty list’. It is an atom not a list data type

---
Working with Lists (1-3)
 Compound data type
 Arbitrary elements; no size limit
 Concise representation in Prolog
 head – tail separator
[<head>|<tail>]
head is an element
tail is list of the same sort
| is used for list construction as well as list dismantling.
 Examples
[1,2,3]
[a, bc, def, gh, i]
[]

---
Working with Lists (2-3)
Examples
[a, bc, def, gh, i]
[]
[1,2,3]
[1, 2 | [3] ]
[1 | [2, 3] ]
[1, 2, 3 | [ ] ]

---
Working with Lists (3-3)
 Think Recursive!
 Example program
Domains
list = integer *
Predicates
length (list, integer)
Clauses
length([],0). %length of an empty list is zero

length ([_|Tail], Len):-


Length (Tail, TailLen), %getting the tail length
Len = TailLen + 1. %the length of list is 1 plus the length of tail
Goal
X = [1,2,3],
length(X,Len).

---
Last and second last element in a list

% lastElement(X,L) :- X is the last element of the list L

lastElement(X,[X]).
lastElement(X,[_|L]) :- lastElement(X,L).

last_but_one(X,[X,_]).
last_but_one(X,[_,Y|Ys]) :- last_but_one(X,[Y|Ys]).

---
Eliminate consecutive duplicates of list
elements.
If a list contains repeated elements they
should be replaced with a single copy of the
element. The order of the elements should not
be changed.

Example:
?- compress([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X).
X = [a,b,c,a,d,e]

---
compress([],[]).
compress([X],[X]).
compress([X,X|Xs],Zs) :- compress([X|Xs],Zs).
compress([X,Y|Ys],[X|Zs]) :- X \= Y,
compress([Y|Ys],Zs).

---
Sorting
sorted ([ ]).
sorted ([X]).
sorted ([X, Y | list]) :- X <= Y, sorted ([Y | list]).

---
List Membership
 List membership is tested with the member predicate, defined by
member(X, [X|T]).
member(X, [H|T]) :- member(X, T).

 ?- member(b, [a,b,c]).
 Execution:
member(b, [a,b,c]) does not match predicate member(X1, [X1|T1])
member(b, [a,b,c]) matches predicate member(X1, [H1|T1])
with X1 = b, H1 = a, and T1 = [b,c]
Sub-goal to prove:member(X1, T1) with X1 = b and T1 = [b,c]
member(b, [b,c]) matches predicate member(X2, [X2|T2])
with X2 = b and T2 = [c]
The sub-goal is proven, so member(b, [a,b,c]) is proven (deduced)

 Note: variables are "local" to a clause (just like the formal arguments
of a function)
Local variables such as X1 and X2 are used to indicate a match of a
(sub)-goal and a head predicate of a clause
---
Example of a user-defined
data type: set.
 set membership -- same as list membership
 subset
subset( [ A | X ], Y ) :- member( A, Y ), subset( X, Y ).
subset( [ ], Y ). % The empty set is a subset of every set.

 intersection
% Assumes lists contain no duplicate elements.
intersection( [ ], X, [ ] ).
intersection( [ X | R ], Y, [ X | Z ] ) :- member( X, Y ), !, intersection( R, Y, Z ).
intersection( [ X | R ], Y, Z ) :- intersection( R, Y, Z ).

 union
union( [ ], X, X ).
union( [ X | R ], Y, Z ) :- member( X, Y ), !, union( R, Y, Z ).
union( [ X | R ], Y, [ X | Z ] ) :- union( R, Y, Z ).

---
The not operator
member (Element, [Element | _ ]) :- !.
member (Element, [_ | List]) :-
member(Element, List).

member (X, [ 1, 2, 3]).

not(not(member(X, [1, 2, 3]))).

---
Puzzles- Who owns the zebra
Zebra files

---
Puzzles- Who owns the zebra
 Try solving this puzzle on your own.
 Now imagine writing a computer program to solve it.
 Which was more difficult?
 This is an example of a completely specified solution
which doesn't appear to be specified at all. The
constraints are such that the answer is unique, but they
are stated in such a way that it is not at all obvious (to
this human, at least) what the answer is.
 In Prolog, we could express each of these specifications,
then let Prolog's search strategy (database search
engine, automated theorem prover) search for a solution.
 We don't have to worry about how to solve the problem
-- we only have the specify what is to be solved.

---
Zebra Puzzle
Prolog program

---
Expert system
 A simple medical expert system
 relieves(Drug, Symptom).
relieves(aspirin, headache).
relieves(aspirin, moderate_pain).
relieves(aspirin, moderate_arthritis).
relieves(aspirin_codine_combination, severe_pain).
relieves(cough_cure, cough).
relieves(pain_gone, severe_pain).
relieves(anti_diarrhea, diarrhea).
relieves(de_congest, cough).
relieves(de_congest, nasal_congestion).
relieves(penicilline, pneumonia).
relieves(bis_cure, diarrhea).
relieves(bis_cure, nausea).
relieves(new_med, headache).
relieves(new_med, moderate_pain).
relieves(cong_plus, nasal_congestion).

---
 aggravates(Drug, Condition).
aggravates(aspirin, asthma).
aggravates(aspirin, peptic_ulcer).
aggravates(anti-diarrhea, fever).
aggravates(de_congest, high_blood_pressure).
aggravates(de_congest, heart_disease).
aggravates(de_congest, diabetes).
aggravates(de_congest, glaucoma).
aggravates(penicilline, asthma).
aggravates(de_congest, high_blood_pressure).
aggravates(bis_cure, diabetes).
aggravates(bis_cure, fever).

---
should_take(Person, Drug) :-
complains_of(Person, Symptom),
relieves(Drug, Symptom),
not(unsuitable_for(Person, Drug)).

unsuitable_for(Person, Drug) :-
aggravates(Drug, Condition),
suffers_from(Person, Condition).

complains_of(ali, headache).
suffers_from(ali, peptic_ulcer).

?- should_take(ali, Drug).
Drug = new_med;

---
Inference Illustration
Example Search Space
G

b1 b2

f1 f2 f10 f1 f2 f10

f1 f2 f10 f1 f2 f10 f1 f2 f10 f1 f2 f10

b1 b2 b1 b2 b1 b2 b1 b2
DFS
---
Flow Control
 The cut Predicate (aka ‘!’)
 It is actually a goal, not an operator
 It always succeeds immediately but
cannot be re-satisfied through back-
tracking.
 As a side-effect, sub-goals to its left
in a compound goal also cannot be re-
satisfied.

---
The cut Predicate
a, b, !, c, d.

If both a and b succeed but c fails


then the whole predicate fails, it is a
waste of time to re-satisfy a or b.

---
Flow Control
The cut Predicate (aka ‘!’)
G
brother(X,Y):-
X<>Y,
father(Z,X),
b1 b2
cut ,
father(Z,Y).
f1 f2 f10 f1 f2 f10
cut cut

f1 f2 f10 f1 f2 f10 f1 f2 f10 f1 f2 f10

b1 b2 b1 b2 b1 b2 b1 b2

---
Typical Prolog Problem (1-4)
 Implement an INHERITANCE EXPERT SYSTEM that should
provide distribution of wealth of a person’s wealth (in Rupees)
among his/her inheritors according to the following inheritance law.

Person has only one child and that is a daughter then daughter gets 1/3.
Person has only daughters (more than one) then daughters get 2/3 total
in equal shares.
Person has any children then parent gets 1/6 each.
Person has no children, no brothers or sisters then mother gets 1/3 and
father gets 2/3.
Person has brothers and sisters but only one parent alive then parent
gets 1/6 and brothers and sisters get 1/6 total in equal shares.
Person has children including at least one boy and some amount is left
to be inherited according to the above heads (rules), each male child
gets twice the amount each female child gets.
Any amount that could not be inherited according to the above heads
(rules), then government gets all of it.

---
Typical Prolog Problem (2-4)
 Facts

D has two wives E and F. D and F had one son A. A married B


and then H, B is divorced from C. D and E have two sons C and
O. O is married to S the daughter of X , the father and W, the
mother. O is also married to P daughter of Q, the father and R,
the mother. Q and R have another daughter T. T recently got
divorced from U, they have one single son V. C and B have a
daughter G. A and H have two sons J and I. I married K and
have three children, one boy M and two girls L and N. Q, R, P
and E are dead by now. The details of wealth in rupees are, A
got 1200, S got 45000 , D got 145, F got 1, J got 10000, K got
10000, L got 10000, T got 10000, Y got 120000, U got 1345340,
I got 10000, O got 1234, M got 23000, B got 1050, C got 100
and V got 1234.

---
Typical Prolog Problem (3-4)
 Output of the program

Inheritance statement for hameed’s Rs 10000

Statement:

<name> <relation> <with> <amount>


Akbar father hameed Rs. 2304
ayesha daughter hameed Rs. 400
chawala son ayesha Rs. 100
Ainee daughter ayesha Rs. 100
Anjum daughter ayesha Rs. 100
Khalid husband ayesha Rs. 100
Governmentnone hameed Rs. 5254

End of inheritance statement

---
Typical Prolog Problem (4-4)
Procedural Language Implementation
Estimated size = 1 kloc
Estimated programming time = 
Estimated Avg. Maintenance time = 1-5 days
Prolog Implementation
Size = .4 kloc (approx)
programming time = 4 days
Avg. Maintenance time = 2 hours

---
Closed World Assumption
 Innocent until proven guilty
 Actually does not mean innocent if
not proven guilty
 True/Fail system versus True/False
 Implication

---
Conclusions
 Declarative
 Simple concise syntax
 Built in tree formation and backtracking
 Readable code
 Relatively case and type insensitive
 Suitable for …
Problem Solving / Searching
Expert Systems / Knowledge Representation
Language Processing / Parsing and NLP
Game Playing
 Efficiency
 Left Recursion
 Double trouble; learning curve
 Lack of standardization

---
Books
Prolog Programming for AI by Ivan Bratko
Visual Prolog; Language Tutorial by PDC

---
Compilers
PDC Visual Prolog
SWI Prolog
Bin-Prolog
K-Prolog
Prolog ++
Many more…

---

You might also like