Title: Logic Programming
1Logic Programming
- Logic-based
- Adopt the syntax from logic for both data and
programs - A logic variable is a symbol for an object in a
domain - Use resolution to infer new propositions from
given ones - Declarative state what should be done rather
than how - Language features of Prolog
- A program consists of relations defined by facts
and rules - Pattern matching
- Recursion
- Nondeterminism realized through backtracking
2A Brief History
- Robinsons resolution theorem prover (65)
- Colmerauers NLP project and Q system (early
70s) - Kowalskis Horn clauses and SLD resolution (early
70s) - D.H.D. Warrens work in the implementation (late
70s) - Japanese Fifth Generation Project and follow-up
projects in Europe and USA (early 80s) - Constraint logic programming (late 80s)
3Syntax of Prolog
- Term
- Atom
- string of letters, digits, and '_' starting with
a low-case letter - string of characters enclosed in quotes
- Number
- integer real
- Variable
- string of letters, digits and '_' starting with a
capital letter or '_'
4Syntax of Prolog (Cont)
- Structure
- f(t1,t2,...,tn)
- f is an atom, called the functor of the structure
- t1,t2,...,tn are terms
- List
- '.'(H,T) gt HT
- '.'(1,'.'(2,'.'(3,))) gt 1,2,3
5Syntax of Prolog (Cont)
- Clause
- Fact
- p(t1,t2,...,tn)
- Rule
- H - B1,B2,...,Bm.
- Predicate
- a sequence of clauses
- Program
- a set of predicates
- Query
Head
Body
6Syntax Examples
father(terach,abraham).male(terach).
parent(Parent,Child)-father(Parent,Child). parent
(Parent,Child)-mother(Parent,Child). uncle(Uncle,
Person) - brother(Uncle,Parent),
parent(Parent,Person).
?-parent(Parent,abraham).
7Unification
- t1 t2 succeeds if
- t1 and t2 are identical
- there exists a substitution q for the variables
in t1 and t2 such that t1q t2q.
f(X,b)f(a,Y). Xa Yb
q X/a, Y/b
8Unification Examples
assignment test test matching unification
without occur checking
?-X1. X1 ?- f(a,b)f(a,b). yes ?- ab. no ?-
f(X,Y)f(a,b) Xa Yb ?-f(X,b)f(a,Y). Xa Yb ?-X
f(X). Xf(f(......
9Unification
- unify(t1,t2)
- if t1 is a variable, then bind t1 to t2
- if t2 is a variable, then bind t2 to t1
- if t1 and t2 are both atomic values
- if t1 and t2 are identical return true
- otherwise, return false
- t1f(a1,...,an) and t2g(b1,...,bm)
- if f ! g m ! n return false
- return unify(a1,b1) ... unify(an,bm)
10Operational Semantics of Prolog (Resolution)
G0 initial query Gi (A1,A2,...,An) H-B1
,...,Bm A1qH1q Gi1 (B1,...,Bm,A2,...,An)q
Succeed if Gk is empty for some k.Backtrack if
Gk is a dead end (no clause can be used).
11Deductive Database
parent(Parent,Child)-father(Parent,Child). parent
(Parent,Child)-mother(Parent,Child). uncle(Uncle,
Person) - brother(Uncle,Parent),
parent(Parent,Person). sibling(Sib1,Sib2) -
parent(Parent,Sib1), parent(Parent,Sib2),
Sib1 \ Sib2. cousin(Cousin1,Cousin2) -
parent(Parent1,Cousin1), parent(Parent2,Cousin
2), sibling(Parent1,Parent2).
12Exercise
- Will the following unification operations succeed
or fail? If they succeed, what are the
substitutions? - point(A,B) point(1,2)
- point(A,B) point(X,Y,Z)
- plus(2,2) 4
- (2,D) (E,2)
- tri(point(-1,0),P2,P3) tri(P1,point(1,0),point(0
,Y))
13Exercise
- Define the following relations
- son(X,Y) -- X is a son of Y
- daughter(X,Y) -- X is a daughter of Y
- grandfather(X,Y) -- X is the grandfather of Y
- grandparent(X,Y) -- X is a grandparent of Y
- ancestor(X,Y) X is an ancestor of Y
14Built-ins in Prolog
- Unification
- T1 T2
- T1 \ T2
- Arithmetic
- X is Exp
- Exp Exp, Exp \ Exp
- Exp gt Exp, Exp gt Exp
- Exp lt Exp, Exp lt
X can be a variable or a ground expression Exp
must be a groundexpression
15Examples(, \, is, , \, gt, gt, lt, lt)
16Built-ins in Prolog (cont.)
- arg(N,T,A)
- The Nth argument of T is A
- functor(T,F,N)
- the functor of T is F/N.
- T1T2
- T1 and T2 are identical
- T1 \ T2
- T1 and T2 are not identical
17Examples(arg, functor, , \)
18Recursive Programming
- Recursively defined data structures
- S-expressions
- 0, s(0), s(s(0)),
- Lists
- , XL
- Binary trees
- void, t(N,L,R)
19Recursive Programming on S-Expressions
- Definition of S-Expressions
- 0, s(0), s(s(0)),....
- sum(X,Y,Z) -- XY makes Z
- prod(X,Y,Z) -- XY makes Z
sum(0,Y,Y). sum(s(X),Y,s(Z))-sum(X,Y,Z).
prod(0,Y,0). prod(s(X),Y,Z)- prod(X,Y,Z1),
sum(Z1,Y,Z).
20Recursive Programming on S-Expressions (Cont.)
- Conversion of integers to s-expressions
int2s(0,0). int2s(N,s(S))- Ngt0, N1 is
N-1, int2s(N1,S).
21Exercise
- Define the following arithmetic operations on
natural numbers. - power(X,Y,Z) XYZ
- factorial(X,Y) X!Y
- lt(X,Y) X is less than Y
- one_hundred(X) X 100 (s(s(....(s(0)))...)
- sum_1_to_100(X) X 12...100
22Recursive Programming on Lists
- A list is a special structure whose functor is
'.'/2 -
- '.'(H,T) gt HT
- '.'(1,'.'(2,'.'(3,))) gt 1,2,3
- Unification of lists
- XXs1,2,3 X 1 Xs2,3
- 1,2,3 12X X3
- 1,23 1X X23
23Relations on Lists
- isList(Xs)
- member(X,Xs)
- append(Xs,Ys,Zs)
- length(Xs,N)
isList(). isList(XXs)-isList(Xs).
member(X,XXs). member(X,_Xs)-member(X,Xs).
append(,Ys,Ys). append(XXs,Ys,XZs)-append
(Xs,Ys,Zs).
length(,0). length(XXs,N)-length(Xs,N1),N
is N11.
24Exercise
- Implement the following predicates.
- length(Xs,N)
- the length of Xs is N
- last(X,Xs)
- X is the last element of Xs.
- prefix(Pre,Xs)
- Pre is a prefix of Xs.
- suffix(Pos,Xs)
- suffix is a postfix of Xs
- reverse(Xs,Ys)
- Ys is the reverse of Xs
- sum(Xs,N)
- N is the sum of the integers in the list Xs
- sum1(Xs,Ys)
- assume Xs is x1,x2,...,xn, then Ys will be
y1,y2,...,yn where yi is xi1. - sort(L,SortedL)
- use the exchange sort algorithm
25Recursive Programming on Binary Trees
- Representation of binary trees
- Example
void -- empty tree t(N, L,R) -- N node L
Left child R Right child
a
t(a, t(b, void,void), t(c,void,void))
c
b
26Relations on Binary Trees
- isBinaryTree(T)-- T is a binary tree
- count(T,C) -- C is the number of nodes in T.
isBinaryTree(void). isBinaryTree(t(N,L,R))- isBi
naryTree(L), isBinaryTree(R).
count(void,0). count(t(N,L,R),N)- count(L,N1),
count(R,N2), N is N1N21.
27Relations on Binary Trees (Cont.)
- preorder(T,L)
- L is a pre-order traversal of the binary tree T.
preorder(void,). preorder(t(N,Left,Right),L)-
preorder(Left,L1), preorder(Right,L2), append(N
L1,L2,L).
28Exercise
- Write the following predicates on binary trees.
- leaves(T,L) L is the list of leaves in T. The
order is preserved. - equal(T1,T2) T1 and T2 are the same tree.
- postorder(T,L) L is the post-order traversal of
T.
29Tail Recursive Programs and Difference Lists
- Recursion is slower and consumes more space than
iteration. - Prolog compilers performs Tail-Recursion-Optimizat
ion, which converts tail recursion into
iteration. - In general, tail-recursive programs are more
efficient than non-tail-recursive programs.
30Tail-Recursive PredicatesExample product
prod(0,Y,0). prod(s(X),Y,Z)- prod(X,Y,Z1), sum(
Z1,Y,Z).
Accumulator
prod(X,Y,Z)- prod(X,Y,0,Z). prod(0,Y,Z,Z). prod
(s(X),Y,Z0,Z)- sum(Y,Z0,Z1), prod(X,Y,Z1,Z).
31Example length
length(,0). length(XXs,N)- length(Xs,N1),
N is N11.
length(Xs,N)- length(Xs,0,N). length(,N,N). l
ength(XXs,N0,N)- N1 is N01, length(Xs,N1,N)
.
32Example reverse
reverse(,). reverse(XXs,Zs)- reverse(Xs,Y
s), append(Ys,X,Zs).
reverse(Xs,Ys)- reverse(Xs,,Ys). reverse(,Y
s,Ys). reverse(XXs,Ys0,Ys)- reverse(Xs,XYs0
,Ys).
33Example count
count(void,0). count(t(N,L,R),N)- count(L,N1),
count(R,N2), N is N1N21.
count(T,N)- count(T,0,N). count(void,N,N). coun
t(t(N,L,R),N0,N)- N1 is N01, count(L,N1,N2),
count(R,N2,N).
34Difference Lists
leaves(void,). leaves(t(N,void,void),L)-!, L
N. leaves(t(N,Left,Right),L)- leaves(Left,L1),
leaves(Right,L2), append(L1,L2,L).
leaves(T,L)- leaves(T,L,). leaves(void,L,L).
leaves(t(N,void,void),L,LR)-!,LNLR. leaves(t(
N,Left,Right),L,LR)- leaves(Left,L,L1), leaves(
Right,L1,LR).
L- equals L
L-L equals
L-LR equals (L-L1) (L1-LR)
35Exercises
- Define the following predicates and convert them
into tail-recursive ones. - merge(L1,L2,L)
- L is the merge of two sorted lists L1 and L2. L
must be sorted too. - preorder(T,L)
- L is the list of nodes in the binary tree T in
pre-order.
36Backtracking and Its Control
- For a goal and a program, Prolog constructs and
explores the search tree (SLD-tree) through
backtracking, i.e., top-down and from left to
right. - Prolog provides an operator '!' (called cut) for
pruning useless branches.
37The Meaning of Backtracking
Gi (A1,A2,...,An) H-B1,...,Bm A1qH1q
Gi1 (B1,...,Bm,A2,...,An)q
- When Gi1 fails,
- undo the bindings of the variables in Gi
- apply an alternative clause to A1
- A1 fails if no such a clause is available, which
will cause Gi to fail.
38BacktrackingExample
p(X)
p(a). p(b). p(c).
Xa
Xb
Xc
39BacktrackingExample
p(a). q(1). p(b). q(2) p(c).
p(X),q(Y)
Xb
Xa
Xc
q(Y)
q(Y)
q(Y)
Y1
Y2
Y1
Y2
Y1
Y2
40BacktrackingExample-- member
member(X,XXs). member(X,_Xs)-member(X,Xs).
- Can be used in two different ways
- test whether the element is a member of the list
- member(b,a,b,c)
- pickup elements from the list one by one
- member(X,a,b,c)
41BacktrackingExample -- select
- select(Xs,X,Rest)
- X is an element in Xs and Rest is Xs but without
X.
select(XXs,X,Xs). select(XXs,Y,XXs1)-sel
ect(Xs,Y,Xs1).
42BacktrackingExample -- permutation
- permutation(Xs,Ys)
- Ys is a permutation of Xs
permutation(,). permutation(Xs,XYs)-
select(Xs,X,Xs1), permutation(Xs1,Ys).
43Exercises
- Define the following predicates
- subset(Xs,Ys)
- Xs is a subset of Ys. Assume Xs and Ys do not
contain duplicates. - intersect(Xs,Ys,Zs)
- Zs is the intersect of Xs and Ys.
44BacktrackingExample -- permutation sort
- sort(Xs,SortedXs)
- SortedXs is Xs sorted in ascending order
sort(Xs,SortedXs)- permutation(Xs,SortedXs), ge
nerator sorted(SortedXs). test sorted(). sor
ted(X). sorted(X1,X2Xs)- X1ltX2, sorted(
X2Xs).
45BacktrackingN-queens problem
- Find a layout for the N queens on an N by N
chessboard such that no queens attack each other.
Two queens attack each other if they are in the
same row, the same column, or the same diagonal.
Xi the number of the row for the ith
queen. for each two variables Xi and Xj Xi \
Xj not same row Xi\Xj(j-i) not same
diagonal Xi\Xj-(j-i)
46N-queens problem (cont.)
queens(N,Qs)- range(1,N,Ns), permutation(Ns,Qs)
, notAttack(Qs). range(N0,N,Ns)- N0N,NsN
. range(N0,N,Ns)- N0ltN, NsN0Ns1, N1 is
N01, range(N1,N,Ns1).
notAttack(). notAttack(XXs)- notAttack(X,Xs
,1), notAttack(Xs). notAttack(X,,K). notAttack
(X,YYs,K)- X\Y, X\YK, X\Y-K, K1 is
K1, notAttack(X,Ys,K1).
47N-queens problem (cont.)Test partial solutions
ASA
queens(N,Qs)- range(1,N,Ns), queens(Ns,,Qs).
queens(,Qs,Qs). queens(Xs,Qs0,Qs)- select(Xs,
X,Xs1), notAttack(X,Qs0,1), queens(Xs1,XQs0,Q
s).
48Exercises
- 1.Write a program to solve the following puzzle.
- Given eight letters S,E, N, D, M, O, R and Y, one
is required to assign a digit between 0 and 9 to
each letter such that all the letters have
different values and the equation SEND MORE
MONEY is satisfied. - 2. Write a program to color the map of Western
Europe. The map is given in the following.
map(west_europe, region(portugal,P,E), regio
n(spain,E,F,P), region(france,F,E,I,S,B,WG,L
), region(belgium,B,F,H,L,WG), region(holl
and,H,B,WG), region(west_germany,WG,F,A,S,H,
B,L), region(luxembourg,L,F,B,WG),
region(italy,I,F,A,S), region(switzerland,
S,F,I,A,WG), region(austria,A,I,S,WG)).
49Controlling Backtracking
- Use cut to express if-then-else
intersect(,Ys,). intersect(XXs,Ys,XZs)-
member(X,Ys), intersect(Xs,Ys,Zs). intersect(X
Xs,Ys,Zs)- not member(X,Ys), intersect(Xs,Ys,
Zs).
intersect(,Ys,). intersect(XXs,Ys,XZs)-
member(X,Ys),!, intersect(Xs,Ys,Zs). intersect(
XXs,Ys,Zs)- not member(X,Ys), intersect(Xs,Y
s,Zs).
50Controlling Backtracking (Cont.)
- Use cut to express negation-as-failure
not(Call)- call(Call),!, fail. not(Call).
51The Meaning of Cut
G-A. ...
The search will proceed from here when Br fails
G
A-Bl,!,Br. ...
A
Bl,!,Br
The cut discards the branches of A and Bl.
- A cut prunes all clauses below it.
- A cut prunes all the choices of the subgoals that
occur to the left of it.
52The Cut is Non-logical
- What is the answer of max(2,5,2) for the
following definition? - Are member(X,1,2,3) and not(not(member(X,1,2,3
)) equivalent?
max(X,Y,Y)-YgtX,!. max(X,Y,X).
53Exercises
- How many solutions do the following queries have?
p(a). p(b). p(c). q(1). q(2).
?-p(X),q(Y),!. ?-p(X),!,q(Y). ?-!,p(X),q(Y).
54Exercises (cont.)
- Insert cuts to improve the efficiency of the
following predicates - Explain why not(not(Call)) is not the same as
Call.
range(N0,N,Ns)- N0gtN,NsN. range(N0,N,Ns)-
N0ltN, NsN0Ns1, N1 is N01, range(N1,N,Ns1).
max(X,Y,Z)-XgtY,ZX. max(X,Y,Z)-XltY,ZY.