1 cs 403 - programming languages class 19 november 2, 2000
DESCRIPTION
CS 403, Class 19 Slide # 3 Objectives What is logic, specifically, first order logic How logic programming is related to first order logic How Prolog embodies logic programming Introduction to using PrologTRANSCRIPT
1
CS 403 - Programming LanguagesClass 19November 2, 2000
CS 403, Class 19 Slide # 2
Today’s AgendaStart Chapter 15Assignment:
Read chapter 15 for todayAnnouncement:
No programming assignment today.
CS 403, Class 19 Slide # 3
ObjectivesWhat is logic, specifically, first order logicHow logic programming is related to first order logicHow Prolog embodies logic programmingIntroduction to using Prolog
CS 403, Class 19 Slide # 4
Prolog
PROgramming in LOGicAlgorithm = Logic + ControlLogic = relation R(I,O) between input I and output OControl = method of searching for O that satisfies R(I,O), given input IE.g. Find X and Y such that3*X+2*Y=1X-Y=4
E.g. find array B such thatelements in B are the same as those in Aelements of B are in non-descending order
CS 403, Class 19 Slide # 5
What is Prolog
Prolog is a ‘typeless’ language with a very simple syntax.Prolog is declarative: you describe the relationship between input and output, not how to construct the output from the input (“specify what you want, not how to compute it”)Prolog uses a subset of first-order logic
CS 403, Class 19 Slide # 6
Classical First-Order Logic
simplest form of logical statements is an atomic formula. e.g.man(tom)woman(mary)married(tom,mary)
More complex formulas can be built up using logical connectives:
Everyone define these symbols
, , , , X, X
CS 403, Class 19 Slide # 7
Examples of First Order Logic
smart(tom) dumb(tom)smart(tom) tall(tom) dumb(tom) X married(tom,X) X loves(tom,X) X [married(tom,X) female(X)
human(X)]rich(tom) smart(tom) X mother(john,X) X Y [mother(john,X) mother(john,Y)
Y=X]Note: A B B A
CS 403, Class 19 Slide # 8
Logic programming is based on formulas called Horn rules. These have the form
Examples: X,Y[A(X) B(X,Y) C(Y)] X[A(X) B(X)] X[A(X,d) B(X,e)] A(c,d) B(d,e) X A(X) X A(X,d) A(c,d)
]B...BB[A x,..., j21k1 ∧∧∧←∀x
Horn Rules
CS 403, Class 19 Slide # 9
Horn Rules (cont.) Note that atomic formulas are also Horn
rules, often called facts. A set of Horn rules is called a Logic
Program.
CS 403, Class 19 Slide # 10
Logical Inference with Horn Rules
Logic programming is based on a simple idea: From rules and facts, derive more facts.Example 1. Given the facts and rules:
1. A 2. B 3. C 4. E A B 5. F C E 6. G E F
From 1, derive E; from 2, derive F; from 3, derive G.
CS 403, Class 19 Slide # 11
Logical Inference
Example 2: Given these facts:man(plato)man(socrates)
and this rule: X [mortal(X) man(X)]
derive:mortal(plato), mortal(socrates).
CS 403, Class 19 Slide # 12
Recursive InferenceExample, given
(1) X[mortal(son_of(X)) mortal(X)](2) mortal(plato)
derive:mortal(son_of(plato))(using X=plato)mortal(son_of(son_of(plato)))(using X=son_of(plato))mortal(son_of(son_of(son_of(plato))))(using X=son_of(son_of(plato)))
CS 403, Class 19 Slide # 13
Prolog NotationA rule:
X [p(X) (q(X) r(X))]is written as
p(X) q(X), r(X).Prolog conventions:
variables begin with upper case (A, B, X, Y, Big, Small, ACE) constants begin with lower case (a, b, x, y, plato, aristotle)
Query = list of facts with variables, e.g. mortal(X) sorted([5,3,4,9,2], X) sonOf(martha,S), sonOf(george,S)
Prolog program = facts+rules+query
CS 403, Class 19 Slide # 14
Prolog Syntax< fact > < term > .< rule > < term > :- < terms > .< query > < terms > .
< term > < number > | < atom > | <variable>
| < atom > ( < terms > )
< terms > < term > | < term > , < terms >
CS 403, Class 19 Slide # 15
Constructors like student and “.” are called functors in Prolog
SyntaxIntegersAtoms: user defined, supplied
name starts with lower case: john, student2Variables
begin with upper case: Who, X ‘_’ can be used in place of variable name
Structures student(ali, freshman, 194).
Lists [x, y, Z ] [ Head | Tail ]
syntactic sugar for . ( Head, Tail ) [ ]
CS 403, Class 19 Slide # 16
Prolog Introduction/* list of facts in prolog, stored in an ascii file, ‘family.pl’*/mother(mary, ann).mother(mary, joe).mother(sue, marY ).
father(mike, ann).father(mike, joe).
grandparent(sue, ann).
CS 403, Class 19 Slide # 17
Prolog Introduction (cont.) /* reading the facts from a file */ ?- consult ( family). %family compiled, 0.00 sec, 828 bytes Comments are either bound by “/*”,”*/” or any
characters following the “%”. Structures are just relationships. There are no
inputs or outputs for the variables of the structures. The swipl documentation of the built-in predicates
does indicate how the variables should be used.pred(+var1, -var2, +var3).
+ indicates input variable- indicates output variable
CS 403, Class 19 Slide # 18
/* Prolog the order of the facts and rules is the order it is searched in *//* Variation from pure logic model */
2 ?- father( X, Y ).
X = mike /* italics represents computer output */Y = ann ; /* I type ‘;’ to continue searching the data base */
X = mikeY = joe ;
no
3 ?- father( X, joe).
X = mike ;
no
CS 403, Class 19 Slide # 19
Rulesparent( X , Y ) :– mother( X , Y ). /* If mother( X ,Y ) then
parent( X ,Y ) */parent( X , Y ) :– father( X , Y ).
/* Note: grandparent(sue, ann). redundant *//* if parent( X ,Y ) and parent(Y,Z ) then grandparent( X ,Z
). */
Define grandparent
grandparent( X , Z ) :– parent( X , Y ),parent(Y, Z ).
CS 403, Class 19 Slide # 20
mother(mary, ann).mother(mary, joe).mother(sue, marY ).father(mike, ann).father(mike, joe).
parent( X , Y ) :– mother( X , Y ). parent( X , Y ) :– father( X , Y ).
?- parent( X , joe).X = mary yes
parent(X,Y) := mother(X,joe).
?- parent(X,joe). X=X,Y=joe
mother(mary,ann). /* fails */mother(mary,joe). /* succeeds */
?- mother(X,joe).
binding
CS 403, Class 19 Slide # 21
?- parent( X , ann), parent( X , joe).X = mary;X = mikeyes
?- grandparent(sue, Y ).Y = ann;Y = joeyes
CS 403, Class 19 Slide # 22
Tracing exercise/* specification of factorial n! */factorial(0,1). factorial(N, M):– N1 is N – 1, factorial (N1, M1), M is N*M1.
Now you do it
CS 403, Class 19 Slide # 23
Solution
CS 403, Class 19 Slide # 24
Recursion in Prologtrivial, or boundary cases‘general’ cases where the solution is constructed from solutions of (simpler) version of the original problem itself.What is the length of a list ?THINK:The length of a list, [ e | Tail ], is 1 + the length of Tail What is the boundary condition?
The list [ ] is the boundary. The length of [ ] is 0.
CS 403, Class 19 Slide # 25
Recursion
Where do we store the value of the length?-- accumulator --
length( [ ], 0 ). length([H | T], N) :- length(T,Nx), N is Nx + 1
mylength( [ ], 0).mylength( [X | Y], N):–mylength(Y, Nx), N is Nx+1.
? – mylength( [1, 7, 9], X ).X = 3
CS 403, Class 19 Slide # 26
Recursion
? - mylength(jim, X ).no? - mylength(Jim, X ).Jim = [ ]X = 0mymember( X , [X | _ ] ).mymember( X , [ _ | Z ] ) :– mymember( X , Z ).
CS 403, Class 19 Slide # 27
Recursion% equivalently: However swipl will give a warning % Singleton variables : Y Wmymember( X , [X | Y] ).mymember( X , [W | Z ] ) :– mymember( X , Z ).
1?–mymember(a, [b, c, 6] ).no2? – mymember(a, [b, a, 6] ).yes3? – mymember( X , [b, c, 6] ).X = b;X = c;X = 6;no
CS 403, Class 19 Slide # 28
Appending Lists IThe Problem: Define a relation append(X,Y,Z) to mean that X appended to Y yields Z
The Program: append([], Y, Y).append([H|X], Y, [H|Z]) :-
append(X,Y,Z).
CS 403, Class 19 Slide # 29
Watch it work: ?- [append]. ?- append([1,2,3,4,5],[a,b,c,d],Z).Z = [1,2,3,4,5,a,b,c,d]?;no ?- append(X,Y,[1,2,3]). X = [] Y = [1,2,3]?;X = [1] Y = [2,3]?;X = [1,2] Y = [3]?;X = [1,2,3] Y = []?; no ?-
CS 403, Class 19 Slide # 30
Watch it work: ?- append([1,2,3],Y,Z).Z = [1,2,3|Y]
CS 403, Class 19 Slide # 31
Length of Lists IThe Problem: Define a relation llength(L,N) to mean that the length of the list L is N.The Program:
llength([],0).llength([X|Z],N):- llength(Z,M), N is
M + 1.
CS 403, Class 19 Slide # 32
Watch it work: ?- [length]. ?- llength([a,b,c,d],M).M=4
CS 403, Class 19 Slide # 33
Length of Lists IIThe Program:
llength([],0).llength([X|Z],N) :- N is M + 1,
llength(Z,M).
CS 403, Class 19 Slide # 34
Watch it work: ?- [length2]. ?- llength([a,b,c,d],M).uncaught exception: error(instantiation_error,(is)/2)
CS 403, Class 19 Slide # 35
Control in Prolog IHow Prolog tries to solve a query like:
<query1>, <query2>, .... , <queryN>This is the control side of the equation:
Algorithm=Logic+Control
Step 1: Find Things that solve <query1>, if none then fail else goto Step 2Step 2: Do the things found from the previous step allow more things to be found that solve <query2>? If not then go back to step1 else goto step 3.......
CS 403, Class 19 Slide # 36
Control in Prolog IProlog tries to solve the clauses from left to right If there is a database file around it will use it in a similarly sequential fashion.1. Goal Order: Solve goals from left to right. 2. Rule Order: Select the first applicable rule, where first refers to their order of appearance in the program/file/database
CS 403, Class 19 Slide # 37
Control in Prolog IIThe actual search algorithm is:
1. start with a query as the current goal.2. WHILE the current goal is non-empty
DO choose the leftmost subgoal ;IF a rule applies to the subgoalTHEN select the first applicable rule;
form a new current goal;ELSE backtrack;SUCCEED
CS 403, Class 19 Slide # 38
Control in Prolog IINote 1: Thus the order of the queries is of paramount importance .Note 2: The general paradigm in Prolog is Guess then Verify: Queries with the fewest solutions should come first, followed by those that filter or verify these few solutions
CS 403, Class 19 Slide # 39
Binary Search Trees I
An example of user defined data structures.The Problem: Recall that a binary search tree (with integer labels) is either : 1. the empty tree empty,or2. a node labelled with an integer N, that has a left subtree and a right subtree, each of which is a binary search tree such that the nodes in the left subtree are labelled by integers strictly smaller than N, while those in the right subtree are strictly greater than N.
CS 403, Class 19 Slide # 40
Data Types in PrologThe primitive data types in prolog can be combined via structures,to form complex datatypes:
<structure>::= <functor>(<arg1>,<arg2>,...)Example In the case of binary search trees we have:
<bstree> ::= empty | node(<number>, <bstree>, <bstree>)
node(15,node(2,node(0,empty,empty), node(10,node(9,node(3,empty,empty), empty), node(12,empty,empty))), node(16,empty,node(19,empty,empty)))
CS 403, Class 19 Slide # 41
Binary Search Trees IIThe Problem: Define a unary predicate isbstree which is true only of those trees that are binary search trees .The Program
isbtree(empty).isbtree(node(N,L,R)):- number(N),isbtree(L),isbtree(R),
smaller(N,R),bigger(N,L).
smaller(N,empty). smaller(N, node(M,L,R)) :- N < M, smaller(N,L), smaller(N,R).
bigger(N, empty). bigger(N, node(M,L,R)) :- N > M, bigger(N,L), bigger(N,R).
CS 403, Class 19 Slide # 42
Watch it work: ?- [btree]. ?- isbtree(node(9,node(3,empty,empty),empty)).true ?yes
CS 403, Class 19 Slide # 43
Binary Search Trees IIIThe Problem: Define a relation which tells whether a particular number is in a binary search tree .
mymember(N,T) should be true if the number N is in the tree T.
The Program mymember(K,node(K,_,_)).mymember(K,node(N,S,_)) :- K < N,mymember(K,S).mymember(K,node(N,_,T)) :- K > T,mymember(K,T).
CS 403, Class 19 Slide # 44
Watch it work: ?- [btree]. ?- [mymember]. ?- member(3, node(10,node(9,node(3,empty,empty),empty), node(12,empty,empty))).true ?yes
CS 403, Class 19 Slide # 45
Unification
Unification is a more general form of pattern matching. In that pattern variables can appear in both the pattern and the target.The following summarizes how unification works:1. a variable and any term unify2. two atomic terms unify only if they are identical3. two complex terms unify if they have the same functor and their arguments unify .
CS 403, Class 19 Slide # 46
Prolog Search Trees Summary
1. Goal Order affects solutions 2. Rule Order affects Solutions3. Gaps in Goals can creep in4. More advanced Prolog programming manipulates the searching
CS 403, Class 19 Slide # 47
Sublists (Goal Order) Two definitions of S being a sublist of Z use:
myappend([], Y, Y).myappend([H|X], Y, [H|Z]) :- myappend(X,Y,Z).
& myprefix(X,Z) :- myappend(X,Y,Z).mysuffix(Y,Z) :- myappend(X,Y,Z).
Version 1sublist1(S,Z) :- myprefix(X,Z), mysuffix(S,X).
Version 2sublist2(S,Z) :- mysuffix(S,X), myprefix(X,Z).
Version 3sublist3(S,Z) :- mysuffix(Y,Z), myprefix(S,Y).
CS 403, Class 19 Slide # 48
Watch them work:| ?- [sublist].consulting....sublist.plyes| ?- sublist1([e], [a,b,c]).
no| ?- sublist2([e], [a,b,c]).
Fatal Error: global stack overflow …
CS 403, Class 19 Slide # 49
Version 1
So what’s happening? If we ask the question:sublist1([e], [a,b,c]).
this becomesprefix(X,[a,b,c]), suffix([e],X).
and using the guess-query idea we see that the first goal will generate four guesses:
[] [a] [a,b] [a,b,c]
none of which pass the verify goal, so we fail.
CS 403, Class 19 Slide # 50
Version 2On the other hand, if we ask the question:sublist2([e], [a,b,c]) this becomes suffix([e],X),prefix(X,[a,b,c]). using the guess-query idea note:Goal will generate an infinite number of guesses.
[e] [_,e] [_,_,e] [_,_,_,e] [_,_,_,_,e] [_,_,_,_,_,e]....
None of which pass the verify goal, so we never terminate