Lecture 22-26 Prolog
Lecture 22-26 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
---
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
---
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
---
PROLOG Paradigm
Examples (Rules)
English PROLOG
---
PROLOG Paradigm
Examples (Queries)
English PROLOG
---
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 _
---
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
?- 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 pq Ahmed is father of Belal or
r : Aslam is uncle of Belal Ahmed is brother of Aslam
---
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
---
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.
---
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
---
Last and second last element in a list
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).
---
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
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.
---
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
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
---
Typical Prolog Problem (3-4)
Output of the program
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…
---