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d!d`
0bbg47d7dv0b(p8phuʚ;I6ʚ;<4ddddb{
0bb:2___PPT9/0?:Lecture On Chapter TwentyTwo ,CS431, Dr. Adam WebberO=@AA Third Look At Prolog
OutlineWNumeric computation in Prolog
Problem space search
Knapsack
8queens
Farewell to Prolog633Unevaluated TermsProlog operators allow terms to be written more concisely, but are not evaluated
These are all the same Prolog term:
That term does not unify with 7$Evaluating ExpressionsThe predefined predicate is can be used to evaluate a term that is a numeric expression
is(X,Y) evaluates the term Y and unifies X with the resulting atom
It is usually used as an operatordZ=
;Instantiation Is Required
Evaluable PredicatesFor X is Y, the predicates that appear in Y have to be evaluable predicates
This includes things like the predefined operators +, , * and /
There are also other predefined evaluable predicates, like abs(Z) and sqrt(Z), but we will not be using them 4; $"Real Values And Integers
ComparisonsNumeric comparison operators: <, >, =<, >=, =:=, =\=
To solve a numeric comparison goal, Prolog evaluates both sides and compares the results numerically
So both sides must be fully instantiated Comparisons
Equalities In PrologXWe have used three different but related equality operators:
X is Y evaluates Y and unifies the result with X: 3 is 1+2 succeeds, but 1+2 is 3 fails
X = Y unifies X and Y, with no evaluation: both 3 = 1+2 and 1+2 = 3 fail
X =:= Y evaluates both and compares: both 3 =:= 1+2 and 1+2 =:= 3 succeed
Any evaluated term must be fully instantiated2=.=# .X
Example: mylength
Counterexample: mylength
Example: sum
Example: gcd
The gcd Predicate At Work&
Example: factorial
5OutlineWNumeric computation in Prolog
Problem space search
Knapsack
8queens
Farewell to PrologR3 Problem Space SearchProlog s strength is (obviously) not numeric computation
The kinds of problems it does best on are those that involve problem space search
You give a logical definition of the solution
The, let Prolog find it&FFThe Knapsack ProblemYou are packing for a camping trip
Your pantry contains these items:
Your knapsack holds 4 kg.
What choice <= 4 kg. maximizes calories?Greedy Methods Do Not WorkMost calories first: bread only, 9200
Lightest first: peanut butter + pasta, 11300
(Best choice: peanut butter + baby food, 13600)SearchNo algorithm for this problem is known that
Always gives the best answer, and
Takes less than exponential time
So bruteforce search is nothing to be ashamed of here
That s good, since search is something Prolog does really well6,Cv,CvRepresentationWe will represent each food item as a term food(N,W,C)
Pantry in our example is [food(bread,4,9200), food(pasta,2,4500), food(peanutButter,1,6700), food(babyFood,3,6900)]
Same representation for knapsack contentsTZ+ a`aA*lf
3
}A subsequence of a list is a copy of the list with any number of elements omitted
(Knapsacks are subsequences of the pantry.)}
This decides whether there is a solution that meets the given calorie goal
Not exactly the answer we want& jDecision And OptimizationWe solved the knapsack decision problem
What we wanted to solve was the knapsack optimization problem
To do that, we will use another predefined predicate: findallB*7The findall Predicate&
`findall(X,Goal,L)
Finds all the ways of proving Goal
For each, applies to X the same substitution that made a provable instance of Goal
Unifies L with the list of all those X sa8 Counting The SolutionsThis shows there were four ways of proving subseq(_,[1,2])
Collected a list of 1 s, one for each proof&g+,$+5 Collecting The Instances}The first and second parameters to findall are the same
This collects all four provable instances of the goal subseq(X,[1,2])2~#D,#C
!#Collecting Particular Substitutions"A common use of findall: the first parameter is a variable from the second
This collects all four X s that make the goal subseq(X,[1,2]) provablePZK ,b"
#
$
%
6OutlineWNumeric computation in Prolog
Problem space search
Knapsack
8queens
Farewell to PrologR3 &The 8Queens ProblemxChess background:
Played on an 8by8 grid
Queen can move any number of spaces vertically, horizontally or diagonally
Two queens are in check if they are in the same row, column or diagonal, so that one could move to the other s square
The problem: place 8 queens on an empty chess board so that no queen is in checkNZZQZs_Q'Representation We could represent a queen in column 2, row 5 with the term queen(2,5)
But, it will be more readable if we use something more compact
Since there will be no other pieces no pawn(X,Y) or king(X,Y) we will just use a term of the form X/Y
(We won t evaluate it as a quotient)~Z< af a a% a% (Example NA chessboard configuration is just a list of queens
This one is [2/5,3/7,6/1] .OZ@
a N)
*
+AdequatecThis is already enough to solve the problem: the query legal(X) will find all legal configurations:(dZ7%c,8Queens SolutionOf course that will take too long: it finds all 64 legal 1queens solutions, then starts on the 2queens solutions, and so on
To make it concentrate right away on 8queens, we can give a different query:Example AOur 8queens solution
[8/4, 7/2, 6/7, 5/3, 4/6, 3/8, 2/5, 1/1] $BZ,aA.Room For Improvement0Slow
Finds trivial permutations after the first:1Z10/An ImprovementClearly every solution has 1 queen in each column
So every solution can be written in a fixed order, like this: X=[1/_,2/_,3/_,4/_,5/_,6/_,7/_,8/_]
Starting with a goal term of that form will restrict the search (speeding it up) and avoid those trivial permutations<Zq#cAv0
1
fSince all Xcoordinates are already known to be in range and distinct, these can be optimized a littlegZg2Improved 8Queens Solution6Now much faster
Finds interesting additional solutions63
An ExperimentFails: arguments not sufficiently instantiated
The member condition does not just test inrange coordinates; it generates themBZT 4Another Experiment.Fails: arguments not sufficiently instantiated
The legal(Rest) condition must come first, because it generates the partial solution tested by nocheckRZ5' 7OutlineWNumeric computation in Prolog
Problem space search
Knapsack
8queens
Farewell to Prolog>33W8Parts We Skipped6The cut (!)
A goal that always succeeds, but only once
Used to control backtracking
Exception handling
Systemgenerated or usergenerated exceptions
throw and catch predicates
The API
A small ISO API; most systems provide more
Many public Prolog libraries: network and file I/O, graphical user interfaces, etc.ZHZZIZZZ H.69A Small LanguageWe did not have to skip as much of Prolog as we did of ML and Java
Prolog is a small language
Yet it is powerful and not easy to master
The most important things we skipped are the techniques Prolog programmers use to get the most out of it$
2/Pbr ` f̙` ` ___` 3f3!>?" dd@,?nKd@
n@
`" n?" dd@ @@``@n?" dd@ @@``PR @ ` `p>>>(
Zwgֳgֳ ?0
T Click to edit Master title style!
!:
T`zgֳgֳ ?P0p
RClick to edit Master text styles
Second Level
Third Level
Fourth Level
Fifth Level!
S
`<gֳgֳ ?P
>*
`Ȅgֳgֳ ?
@*
`gֳgֳ ?
@*H
0h? ? f̙ grammars5
@u
(
pF
N
f
6?!
BCqDEF1?p@
BCqDEF1?pp@ N
f
6?
BCaDEF1?`@
BCaDEF1?``@N R
R l
< ?R
BaCPDEF1?O`O`@R
BaCPDEF1?O`@R
ZLgֳgֳ ?@/
T Click to edit Master title style!
!
Z
gֳgֳ ? ` @
W#Click to edit Master subtitle style$
$
`gֳgֳ ?
>*
`gֳgֳ ?
@*
`Hgֳgֳ ?
@*H
0h? ? f̙0`8(
N,mcc I
v*>>>]]
Ndcc
x*>>>]]d
c$ ?
4
NDqcc
>
RClick to edit Master text styles
Second level
Third level
Fourth level
Fifth level!
S
Tcc PIo
v*>>>]]
Tcc P o
x*>>>]]H
0sTh#6 ? ̙33p((
NAcc I
\*>>>]]
N(Kcc
^*>>>]]
TUcc PIo
\*>>>]]
TPcc P o
^*>>>]]H
0sTh#6 ? ̙33`30(
r
S@/
H
0h ? ̙33
$(
r
S=1+3.No? X is 13, Y is 02, X =:= Y.X = 2Y = 2 Yese 2'''''''''H
4
0h ? f̙
<
$(
<
r
<
S0

r
<
Sh{`{
H
<
0h ? f̙^
@
(
@
r
@
SQ{0
{
c
@
0{p
[mylength([],0).mylength([_Tail], Len) : mylength(Tail, TailLen), Len is TailLen + 1.*\ 2['Z
@
0P@
!W? mylength([a,b,c],X).X = 3 Yes? mylength(X,3).X = [_G266, _G269, _G272] YeszX 2'''' ', (H
@
0h ? f̙
0H
:(
H
x
H
c$Hv0

b
H
0z{p
Zmylength([],0).mylength([_Tail], Len) : mylength(Tail, TailLen), Len = TailLen + 1.*[ 2Z'Z
H
0{P@P
2? mylength([1,2,3,4,5],X).X = 0+1+1+1+1+1 YesH3 2''' (H
H
0h ? f̙
zr@L
(
L
x
L
c$40
L
0!p
Lsum([],0).sum([HeadTail],X) : sum(Tail,TailSum), X is Head + TailSum. M 2M',,.
L
0P@
B? sum([1,2,3],X).X = 6 Yes? sum([1,2.5,3],X).X = 6.5YespC 2'''''H
L
0h ? f̙
PP
8(
P
x
P
c$50
2
P
0xN`
gcd(X,Y,Z) : X =:= Y, Z is X.gcd(X,Y,Denom) : X < Y, NewY is Y  X, gcd(X,NewY,Denom).gcd(X,Y,Denom) : X > Y, NewX is X  Y, gcd(NewX,Y,Denom). 2'
P
0`
Note: not just
gcd(X,X,X) 2 2`a RB
P
@
s*DH
P
0h ? f̙
UM D
(
D
r
D
Sָ0
3
D
08@`
? gcd(5,5,X).X = 5 Yes? gcd(12,21,X).X = 3 Yes? gcd(91,105,X).X = 7 Yes? gcd(91,X,7).ERROR: Arguments are not sufficiently instantiated 2'
'
''
''
''2'P=H
D
0h ? f̙7
`T
w(
T
x
T
c$0
D
T
0&
tfactorial(X,1) : X =:= 1.factorial(X,Fact) : X > 1, NewX is X  1, factorial(NewX,NF), Fact is X * NF. u 2u',;s
T
0<4 `
_? factorial(5,X).X = 120 Yes? factorial(20,X).X = 2.4329e+018 Yes? factorial(2,X).No` 2'''''''H
T
0h ? f̙
0(
x
c$`i0
x
c$d
P0p
H
0h ? f̙
\
$(
\
r
\
Sx0
r
\
SpP0p
H
\
0h ? f̙
LD45d
(
d
r
d
S`0
r
d
S`0`
\F 
3d
``P@ +
1d
+c@
d
d
6`+
CItem
""Z
d
s*r@
d
d
6L\{!
RWeight in kilograms
""Z
d
s* g@ +
d
+
d
6?
G Calories
"
"Z
d
s* +d@ &
d
&
d
64+&
Dbread
""Z
d
s*&`@ &
d
&
d
6c! &
@4
""Z
d
s* &c@ +&
d
+&
d
6
&
C9200
""Z
d
s* +&d@ &
d
&
d
6Э+&
Dpasta
""Z
d
s*&`@ &
"d
&
d
64̴!&
@2
""Z
!d
s*& c@ &+
$d
&+
d
6
&
C4600
""Z
#d
s* &+l@ L
&d
L
d
6+L
Lpeanut butter
""Z
%d
s*L`@ L
(d
L
d
6P;! L
@1
""Z
'd
s* Lc@ +L
*d
+L
d
6X]
L
C6700
""Z
)d
s* +Lh@ L
,d
L
d
6+L
H
baby food
"
"Z
+d
s*L`@ L
.d
L
d
6!L
@3
""Z
d
s*L c@ L+
0d
L+
d
6t
L
C6900
""Z
/d
s* L+Z
2d
s*LB
5d
c$DP`PPH
d
0h ? f̙
2*44h
(
h
r
h
S0
r
h
SD` 0
BL 
h
#``P N +
h
+qN
h
h
68+
CItem
""Z
h
s*N
h
h
60x!
RWeight in kilograms
""Z
h
s* uN +
h
+
h
6
G Calories
"
"Z
h
s* +rN &
h
&
h
6+&
Dbread
""Z
h
s*&nN &
h
&
h
62! &
@4
""Z
h
s* &qN +&
h
+&
h
6x6
&
C9200
""Z
h
s* +&rN &
h
&
h
6l+&
Dpasta
""Z
h
s*&nN &
h
&
h
6d!&
@2
""Z
h
s*& qN &+
h
&+
h
6
&
C4600
""Z
h
s* &+zN L
!h
L
"h
6+L
Lpeanut butter
""Z
#h
s*LnN L
$h
L
%h
6˿! L
@1
""Z
&h
s* LqN +L
'h
+L
(h
6ą
L
C6700
""Z
)h
s* +LvN L
*h
L
+h
6H}+L
H
baby food
"
"Z
,h
s*LnN L
h
L
.h
6Z!L
@3
""Z
/h
s*L qN L+
0h
L+
1h
6@G
L
C6900
""Z
2h
s* L+Z
3h
s*LB
4h
c$DP`PPH
h
0h ? f̙
l
$(
l
r
l
S,ȿ0
r
l
SpP0p
H
l
0h ? f̙
p
$(
p
r
p
S0
r
p
SMP0p
H
p
0h ? f̙
x
(
x
x
0(0
/* weight(L,N) takes a list L of food terms, each of the form food(Name,Weight,Calories). We unify N with the sum of all the Weights.*/weight([],0).weight([food(_,W,_)  Rest], X) : weight(Rest,RestW), X is W + RestW./* calories(L,N) takes a list L of food terms, each of the form food(Name,Weight,Calories). We unify N with the sum of all the Calories.*/calories([],0).calories([food(_,_,C)  Rest], X) : calories(Rest,RestC), X is C + RestC.* 2'P
H
x
0h ? f̙

S(


00PP
A/* subseq(X,Y) succeeds when list X is the same as list Y, but with zero or more elements omitted. This can be used with any pattern of instantiations.*/subseq([],[]).subseq([Item  RestX], [Item  RestY]) : subseq(RestX,RestY).subseq(X, [_  RestY]) : subseq(X,RestY). 2'
r

S 0p
H

0h ? f̙
\(
0 p`J
? subseq([1,3],[1,2,3,4]).Yes? subseq(X,[1,2,3]).X = [1, 2, 3] ;X = [1, 2] ;X = [1, 3] ;X = [1] ;X = [2, 3] ;X = [2] ;X = [3] ;X = [] ;No 2'''''''''' '''''' ''''',p
0p@*
INote that subseq can do more than just test whether one list is a subsequence of another; it can generate subsequences, which is how we will use it for the knapsack problem.^ 2
6E
r
Sh0
H
0h ? f̙
z0
(
0] P
z/* knapsackDecision(Pantry,Capacity,Goal,Knapsack) takes a list Pantry of food terms, a positive number Capacity, and a positive number Goal. We unify Knapsack with a subsequence of Pantry representing a knapsack with total calories >= goal, subject to the constraint that the total weight is =< Capacity.*/knapsackDecision(Pantry,Capacity,Goal,Knapsack) : subseq(Knapsack,Pantry), weight(Knapsack,Weight), Weight =< Capacity, calories(Knapsack,Calories), Calories >= Goal. 2'>1" wH
0h ? f̙
C;
(
r
S
0`
!
04``
? knapsackDecision( [food(bread,4,9200), food(pasta,2,4500), food(peanutButter,1,6700), food(babyFood,3,6900)], 4, 10000, X).X = [food(pasta, 2, 4500), food(peanutButter, 1, 6700)] Yesj 2''''''' '''''''''>'PAIH
0h ? f̙
@
$(
r
SK0
r
SЯP0p
H
0h ? f̙
P
$(
r
SL0
r
ShP0p
H
0h ? f̙
p
\(
r
S$0
r
SU 0p
0
0
8? findall(1,subseq(_,[1,2]),L).L = [1, 1, 1, 1] YesH9 2''',&H
0h ? f̙
*(
x
c$O0
x
c$
0
0Z0`
? findall(subseq(X,[1,2]),subseq(X,[1,2]),L).X = _G396L = [subseq([1, 2], [1, 2]), subseq([1], [1, 2]), subseq([2], [1, 2]), subseq([], [1, 2])] YesH 2','s'
H
0h ? f̙<
(
x
c$y0
x
c$/ 00
D
0x( 0@
L? findall(X,subseq(X,[1,2]),L).X = _G312L = [[1, 2], [1], [2], []] YesHM 2'',',:H
0h ? f̙
S(
0K P
9/* legalKnapsack(Pantry,Capacity,Knapsack) takes a list Pantry of food terms and a positive number Capacity. We unify Knapsack with a subsequence of Pantry whose total weight is =< Capacity.*/legalKnapsack(Pantry,Capacity,Knapsack): subseq(Knapsack,Pantry), weight(Knapsack,W), W =< Capacity. : 2:'> :H
0h ? f̙
(
0XW0
/* maxCalories(List,Result) takes a List of lists of food terms. We unify Result with an element from the list that maximizes the total calories. We use a helper predicate maxC that takes four paramters: the remaining list of lists of food terms, the best list of food terms seen so far, its total calories, and the final result.*/maxC([],Sofar,_,Sofar).maxC([First  Rest],_,MC,Result) : calories(First,FirstC), MC =< FirstC, maxC(Rest,First,FirstC,Result).maxC([First  Rest],Sofar,MC,Result) : calories(First,FirstC), MC > FirstC, maxC(Rest,Sofar,MC,Result).maxCalories([First  Rest],Result) : calories(First,FirstC), maxC(Rest,First,FirstC,Result). 2'
1
,
H
0h ? f̙
WO
(
0@
O/* knapsackOptimization(Pantry,Capacity,Knapsack) takes a list Pantry of food items and a positive integer Capacity. We unify Knapsack with a subsequence of Pantry representing a knapsack of maximum total calories, subject to the constraint that the total weight is =< Capacity.*/knapsackOptimization(Pantry,Capacity,Knapsack) : findall(K,legalKnapsack(Pantry,Capacity,K),L), maxCalories(L,Knapsack). 2'b
H
0h ? f̙
O(
0p
? knapsackOptimization( [food(bread,4,9200), food(pasta,2,4500), food(peanutButter,1,6700), food(babyFood,3,6900)], 4, Knapsack).Knapsack = [food(peanutButter, 1, 6700), food(babyFood, 3, 6900)] Yes8 2''''''' '''''''V'bA5H
0h ? f̙
0(
x
c$0
x
c$P0p
H
0h ? f̙
$(
r
SF0
r
S 0p
H
0h ? f̙
0(
x
c$d0
x
c$୳P0p
H
0h ? f̙
LD
(
r
Sp0
r
Sr
0p
R
s*V
CA? \
H
0h ? f̙
0
3(
0{?
/* nocheck(X/Y,L) takes a queen X/Y and a list of queens. We succeed if and only if the X/Y queen holds none of the others in check.*/nocheck(_, []).nocheck(X/Y, [X1/Y1  Rest]) : X =\= X1, Y =\= Y1, abs(Y1Y) =\= abs(X1X), nocheck(X/Y, Rest). 2'P
K
H
0h ? f̙
]U@
(
07?
U/* legal(L) succeeds if L is a legal placement of queens: all coordinates in range and no queen in check.*/legal([]).legal([X/Y  Rest]) : legal(Rest), member(X,[1,2,3,4,5,6,7,8]), member(Y,[1,2,3,4,5,6,7,8]), nocheck(X/Y, Rest). 2'
H
0h ? f̙m
P
(
r
S0
r
St{P0{
0̩
!;? legal(X).X = [] ;X = [1/1] ;X = [1/2] ;X = [1/3]< 2'
''''''''H
0h ? f̙
`
Q(
r
S0
r
SXP0p
%
0ԃ{ppp
W? X = [_,_,_,_,_,_,_,_], legal(X).X = [8/4, 7/2, 6/7, 5/3, 4/6, 3/8, 2/5, 1/1] YesRX 2'"'3'H
0h ? f̙
p
B(
x
c$,0
x
c$ز
0p
R
s*R
s*V
CA?P
H
0h ? f̙
S(
r
S^0
r
SMP0
'
0*{
? X = [_,_,_,_,_,_,_,_], legal(X).X = [8/4, 7/2, 6/7, 5/3, 4/6, 3/8, 2/5, 1/1] ;X = [7/2, 8/4, 6/7, 5/3, 4/6, 3/8, 2/5, 1/1] ;X = [8/4, 6/7, 7/2, 5/3, 4/6, 3/8, 2/5, 1/1] ;X = [6/7, 8/4, 7/2, 5/3, 4/6, 3/8, 2/5, 1/1] 2'"'.''/''/''.'H
0h ? f̙
$(
r
Sh0
r
STƴP0p
H
0h ? f̙
5
(
0Hw
/* eightqueens(X) succeeds if X is a legal placement of eight queens, listed in order of their X coordinates.*/eightqueens(X) : X = [1/_,2/_,3/_,4/_,5/_,6/_,7/_,8/_], legal(X). 2',f<H
0h ? f̙
>6
(
0H0
0nocheck(_, []).nocheck(X/Y, [X1/Y1  Rest]) : % X =\= X1, assume the X's are distinct Y =\= Y1, abs(Y1Y) =\= abs(X1X), nocheck(X/Y, Rest).legal([]).legal([X/Y  Rest]) : legal(Rest), % member(X,[1,2,3,4,5,6,7,8]), assume X in range member(Y,[1,2,3,4,5,6,7,8]), nocheck(X/Y, Rest). 1 21'Hi
r
Sp00
H
0h ? f̙
<4
(
x
c$/0
x
c$h/{P0p
0{p
4r? eightqueens(X).X = [1/4, 2/2, 3/7, 4/3, 5/6, 6/8, 7/5, 8/1] ;X = [1/5, 2/2, 3/4, 4/7, 5/3, 6/8, 7/6, 8/1] ;s 2''.''/''eH
0h ? f̙_
(
r
Sд0
r
S$ʹ0 0p
s
0pj
legal([]).legal([X/Y  Rest]) : legal(Rest),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6(͞6(M~~;r{{K@{K;Q;YiShJS#ї=>Z#uip^ivkgWqDizʯzjt[/LTVb״c3ܫ#JSx\`
$gxy!ʯkcBҏj#J'O84='v<4ISfl8wzjt.?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{}~Root EntrydO)0VPicturesCurrent UserJSummaryInformation(!PowerPoint Document(eDocumentSummaryInformation88> $MSDraw.Drawing.8.202Microsoft Draw 98 Drawing0@ $MSDraw.Drawing.8.202Microsoft Draw 98 Drawing/0DTimes New Roman3bbv0b(
0DMonotype Sorts3bbv0b(
0 DCourier Newts3bbv0b(
01
`.
@n?" dd@ @@``(J<P
$
M34)<j <#7,6U!R+ &
+
%%!%
65 !"#$%&'()+,.012345678/9*:;</X2$]+z6[)N2$J ,7S%ĸp)Nc$@8,g4SdSdv0bppp@<4BdBd`
0b4b<4!d!d`
0b4bg47d7dv0b(p8phdʚ;I6ʚ;<4ddddb{
0bb:2___PPT9/0?:Lecture On Chapter TwentyTwo ,CS431, Dr. Adam WebberO=@A Third Look At Prolog
OutlineWNumeric computation in Prolog
Problem space search
Knapsack
8queens
Farewell to Prolog633Unevaluated TermsProlog operators allow terms to be written more concisely, but are not evaluated
These are all the same Prolog term:
That term does not unify with 7$Evaluating ExpressionsThe predefined predicate is can be used to evaluate a term that is a numeric expression
is(X,Y) evaluates the term Y and unifies X with the resulting atom
It is usually used as an operatordZ=
;Instantiation Is Required
Evaluable PredicatesFor X is Y, the predicates that appear in Y have to be evaluable predicates
This includes things like the predefined operators +, , * and /
There are also other predefined evaluable predicates, like abs(Z) and sqrt(Z) 4;Real Values And Integers
ComparisonsNumeric comparison operators: <, >, =<, >=, =:=, =\=
To solve a numeric comparison goal, Prolog evaluates both sides and compares the results numerically
So both sides must be fully instantiated Comparisons
Equalities In PrologXWe have used three different but related equality operators:
X is Y evaluates Y and unifies the result with X: 3 is 1+2 succeeds, but 1+2 is 3 fails
X = Y unifies X and Y, with no evaluation: both 3 = 1+2 and 1+2 = 3 fail
X =:= Y evaluates both and compares: both 3 =:= 1+2 and 1+2 =:= 3 succeed
Any evaluated term must be fully instantiated2=.=# .X
Example: mylength
Counterexample: mylength
Example: sum
Example: gcd
The gcd Predicate At Work&
Example: factorial
5OutlineWNumeric computation in Prolog
Problem space search
Knapsack
8queens
Farewell to PrologR3 Problem Space SearchProlog s strength is (obviously) not numeric computation
The kinds of problems it does best on are those that involve problem space search
You give a logical definition of the solution
Then let Prolog find it&FFThe Knapsack ProblemYou are packing for a camping trip
Your pantry contains these items:
Your knapsack holds 4 kg.
What choice <= 4 kg. maximizes calories?Greedy Methods Do Not WorkMost calories first: bread only, 9200
Lightest first: peanut butter + pasta, 11300
(Best choice: peanut butter + baby food, 13600)SearchNo algorithm for this problem is known that
Always gives the best answer, and
Takes less than exponential time
So bruteforce search is nothing to be ashamed of here
That s good, since search is something Prolog does really well6,Cv,CvRepresentationWe will represent each food item as a term food(N,W,C)
Pantry in our example is [food(bread,4,9200), food(pasta,2,4500), food(peanutButter,1,6700), food(babyFood,3,6900)]
Same representation for knapsack contentsTZ+ a`aA*lf
3
A subsequence of a list is a copy of the list with any number of elements omitted
(Knapsacks are subsequences of the pantry)
This decides whether there is a solution that meets the given calorie goal
Not exactly the a
"#$%&'()*+,./0123456789:;<=>?@ABCDEFGHIJKLMnswer we want& jDecision And OptimizationWe solved the knapsack decision problem
What we wanted to solve was the knapsack optimization problem
To do that, we will use another predefined predicate: findallB*7The findall Predicate&
`findall(X,Goal,L)
Finds all the ways of proving Goal
For each, applies to X the same substitution that made a provable instance of Goal
Unifies L with the list of all those X sa8 Counting The SolutionsThis shows there were four ways of proving subseq(_,[1,2])
Collected a list of 1 s, one for each proof&g+,$+5 Collecting The Instances}The first and second parameters to findall are the same
This collects all four provable instances of the goal subseq(X,[1,2])2~#D,#C
!#Collecting Particular Substitutions"A common use of findall: the first parameter is a variable from the second
This collects all four X s that make the goal subseq(X,[1,2]) provablePZK ,b"
#
$
%
6OutlineWNumeric computation in Prolog
Problem space search
Knapsack
8queens
Farewell to PrologR3 &The 8Queens ProblemxChess background:
Played on an 8by8 grid
Queen can move any number of spaces vertically, horizontally or diagonally
Two queens are in check if they are in the same row, column or diagonal, so that one could move to the other s square
The problem: place 8 queens on an empty chess board so that no queen is in checkNZZQZs_Q'RepresentationWe could represent a queen in column 2, row 5 with the term queen(2,5)
But it will be more readable if we use something more compact
Since there will be no other pieces no pawn(X,Y) or king(X,Y) we will just use a term of the form X/Y
(We won t evaluate it as a quotient)~Z< ae a a% a% (Example NA chessboard configuration is just a list of queens
This one is [2/5,3/7,6/1] .OZ@
a N)
*
+AdequatecThis is already enough to solve the problem: the query legal(X) will find all legal configurations:(dZ7%c,8Queens SolutionOf course that will take too long: it finds all 64 legal 1queens solutions, then starts on the 2queens solutions, and so on
To make it concentrate right away on 8queens, we can give a different query:Example AOur 8queens solution
[8/4, 7/2, 6/7, 5/3, 4/6, 3/8, 2/5, 1/1] $BZ,aA.Room For Improvement0Slow
Finds trivial permutations after the first:1Z10/An ImprovementClearly every solution has 1 queen in each column
So every solution can be written in a fixed order, like this: X=[1/_,2/_,3/_,4/_,5/_,6/_,7/_,8/_]
Starting with a goal term of that form will restrict the search (speeding it up) and avoid those trivial permutations<Zq#cAv0
1
fSince all Xcoordinates are already known to be in range and distinct, these can be optimized a littlegZg2Improved 8Queens Solution6Now much faster
Finds interesting additional solutions63
An ExperimentFails: arguments not sufficiently instantiated
The member condition does not just test inrange coordinates; it generates themBZT 4Another Experiment.Fails: arguments not sufficiently instantiated
The legal(Rest) condition must come first, because it generates the partial solution tested by nocheckRZ5' 7OutlineWNumeric computation in Prolog
Problem space search
Knapsack
8queens
Farewell to Prolog>33W8Parts We Skipped6The cut (!)
A goal that always succeeds, but only once
Used to control backtracking
Exception handling
Systemgenerated or usergenerated exceptions
throw and catch predicates
The API
A small ISO API; most systems provide more
Many public Prolog libraries: network and file I/O, graphical user interfaces, etc.ZHZZIZZZ H.69A Small LanguageWe did not have to skip as much of Prolog as we did of ML and Java
Prolog is a small language
Yet it is powerful and not easy to master
The most important things we skipped are the techniques Prolog programmers use to get the most out of it$
2/Pb
,
$(
,
r
,
Sg0
r
,
SgP0p
H
,
0h ? f̙
`\
$(
\
r
\
S<0
r
\
SP0p
H
\
0h ? f̙

S(


0PP
A/* subseq(X,Y) succeeds when list X is the same as list Y, but with zero or more elements omitted. This can be used with any pattern of instantiations.*/subseq([],[]).subseq([Item  RestX], [Item  RestY]) : subseq(RestX,RestY).subseq(X, [_  RestY]) : subseq(X,RestY). 2'
r

S 0p
H

0h ? f̙
RJ
(
0p`J
? subseq([1,3],[1,2,3,4]).Yes? subseq(X,[1,2,3]).X = [1, 2, 3] ;X = [1, 2] ;X = [1, 3] ;X = [1] ;X = [2, 3] ;X = [2] ;X = [3] ;X = [] ;No 2'''''''''' '''''' ''''',p
0p@*
INote that subseq can do more than just test whether one list is a subsequence of another; it can generate subsequences, which is how we will use it for the knapsack problem.^ 2
6E
H
0h ? f̙
0(
x
c$0
x
c$pP0p
H
0h ? f̙
Q(
r
S0
r
S0P0p
%
0jppp
W? X = [_,_,_,_,_,_,_,_], legal(X).X = [8/4, 7/2, 6/7, 5/3, 4/6, 3/8, 2/5, 1/1] YesRX 2'"'3'H
0h ? f̙r4y_K 7R9
xy
^(o
H
> $MSDr
Z՜.+,0
Onscreen Shownse7 <Times New RomanMonotype SortsCourier New grammarsMicrosoft Draw 98 DrawingA Third Look At PrologOutlineUnevaluated TermsEvaluating ExpressionsInstantiation Is RequiredEvaluable PredicatesReal Values And IntegersComparisonsComparisonsEqualities In PrologExample: mylengthCounterexample: mylength
Example: sum
Example: gcdThe gcd Predicate At WorkExample: factorialOutlineProblem Space SearchThe Knapsack ProblemGreedy Methods Do Not WorkSearchRepresentationPowerPoint PresentationPowerPoint PresentationPowerPoint PresentationPowerPoint PresentationPowerPoint PresentationDecision And OptimizationThe findall PredicateCounting The SolutionsCollecting The Instances$Collecting Particular SubstitutionsPowerPoint PresentationPowerPoint PresentationPowerPoint PresentationPowerPoint PresentationOutlineThe 8Queens ProblemRepresentationExamplePowerPoint PresentationPowerPoint Presentation Adequate8Queens SolutionExampleRoom For ImprovementAn ImprovementPowerPoint PresentationPowerPoint PresentationImproved 8Queens SolutionAn ExperimentAnother ExperimentOutlineParts We SkippedA Small LanguageFonts UsedDesign TemplateEmbedded OLE Servers
Slide Titles7
&_ve Jozo Dujmovic Jozo Dujmovicerm that is a numeric expression
is(X,Y) evaluates the term Y and unifies X with the resulting atom
It is usually used as an operatordZ=
;Instantiation Is Required
Evaluable PredicatesFor X is Y, the predicates that appear in Y have to be evaluable predicates
This includes things like the predefined operators +, , * and /
There are also other predefined evaluable predicates, like abs(Z) and sqrt(Z) 4;Real Values And Integers
ComparisonsNumeric comparison operators: <, >, =<, >=, =:=, =\=
To solve a numeric comparison goal, Prolog evaluates both sides and compares the results numerically
So both sides must be fully instantiated Comparisons
Equalities In PrologXWe have used three different but related equality operators:
X is Y evaluates Y and unifies the result with X: 3 is 1+2 succeeds, but 1+2 is 3 fails
X = Y unifies X and Y, with no evaluation: both 3 = 1+2 and 1+2 = 3 fail
X =:= Y evaluates both and compares: both 3 =:= 1+2 and 1+2 =:= 3 succeed
Any evaluated term must be fully instantiated2=.=# .X
Example: mylength
Counterexample: mylength
Example: sum
Example: gcd
The gcd Predicate At Work&
Example: factorial
5OutlineWNumeric computation in Prolog
Problem space search
Knapsack
8queens
Farewell to PrologR3 Problem Space SearchProlog s strength is (obviously) not numeric computation
The kinds of problems it does best on are those that involve problem space search
You give a logical definition of the solution
Then let Prolog find it&FFThe Knapsack ProblemYou are packing for a camping trip
Your pantry contains these items:
Your knapsack holds 4 kg.
What choice <= 4 kg. maximizes calories?Greedy Methods Do Not WorkMost calories first: bread only, 9200
Lightest first: peanut butter + pasta, 11300
(Best choice: peanut butter + baby food, 13600)SearchNo algorithm for this problem is known that
Always gives the best answer, and
Takes less than exponential time
So bruteforce search is nothing to be ashamed of here
That s good, since search is something Prolog does really well6,Cv,CvRepresentationWe will represent each food item as a term food(N,W,C)
Pantry in our example is [food(bread,4,9200), food(pasta,2,4500), food(peanutButter,1,6700), food(babyFood,3,6900)]
Same representation for knapsack contentsTZ+ a`aA*lf
3
A subsequence of a list is a copy of the list with any number of elements omitted
(Knapsacks are subsequences of the pantry)
This decides whether there is a solution that meets the given calorie goal
Not exactly the answer we want& jDecision And OptimizationWe solved the knapsack decision problem
What we wanted to solve was the knapsack optimization problem
To do that, we will use another predefined predicate: findallB*7The findall Predicate&
`findall(X,Goal,L)
Finds all the ways of proving Goal
For each, applies to X the same substitution that made a provable instance of Goal
Unifies L with the list of all those X sa8 Counting The SolutionsThis shows there were four ways of proving subseq(_,[1,2])
Collected a list of 1 s, one for each proof&g+,$+5 Collecting The Instances}The first and second parameters to findall are the same
This collects all four provable instances of the goal subseq(X,[1,2])2~#D,#C
!#Collecting Particular Substitutions"A common use of findall: the first parameter is a variable from the second
This collects all four X s that make the goal subseq(X,[1,2]) provablePZK ,b"
#
$
%
6OutlineWNumeric computation in Prolog
Problem space search
Knapsack
8queens
Farewell to PrologR3 &The 8Queens ProblemxChess background:
Played on an 8by8 grid
Queen can move any number of spaces vertically, horizontally or diagonally
Two queens are in check if they are in the same row, column or diagonal, so that one could move to the other s square
The problem: place 8 queens on an empty chess board so that no queen is in checkNZZQZs_Q'RepresentationWe could represent a queen in column 2, row 5 with the term queen(2,5)
But it will be more readable if we use something more compact
Since there will be no other pieces no pawn(X,Y) or king(X,Y) we will just use a term of the form X/Y
(We won t evaluate it as a quotient)~Z< ae a a% a% (Example NA chessboard configuration is just a list of queens
This one is [2/5,3/7,6/1] .OZ@
a N)
*
+AdequatecThis is already enough to solve the problem: the query legal(X) will find all legal configurations:(dZ7%c,8Queens SolutionOf course that will take too long: it finds all 64 legal 1queens solutions, then starts on the 2queens solutions, and so on
To make it concentrate right away on 8queens, we can give a different query:Example AOur 8queens solution
[8/4, 7/2, 6/7, 5/3, 4/6, 3/8, 2/5, 1/1] $BZ,aA.Room For Improvement0Slow
Finds trivial permutations after the first:1Z10/An ImprovementClearly every solution has 1 queen in each column
So every solution can be written in a fixed order, like this: X=[1/_,2/_,3/_,4/_,5/_,6/_,7/_,8/_]
Starting with a goal term of that form will restrict the search (speeding it up) and avoid those trivial permutations<Zq#cAv0
1
fSince all Xcoordinates are already known to be in range and distinct, these can be optimized a littlegZg2Improved 8Queens Solution1Now much faster
Does not bother with permutations3
An ExperimentFails: arguments not sufficiently instantiated
The member condition does not just test inrange coordinates; it generates themBZT 4Another Experiment.Fails: arguments not sufficiently instantiated
The legal(Rest) condition must come first, because it generates the partial solution tested by nocheckRZ5' 7OutlineWNumeric computation in Prolog
Problem space search
Knapsack
8queens
Farewell to Prolog>33W8Parts We Skipped6The cut (!)
A goal that always succeeds, but only once
Used to control backtracking
Exception handling
Systemgenerated or usergenerated exceptions
throw and catch predicates
The API
A small ISO API; most systems provide more
Many public Prolog libraries: network and file I/O, graphical user interfaces, etc.ZHZZIZZZ H.69A Small LanguageWe did not have to skip as much of Prolog as we did of ML and Java
Prolog is a small language
Yet it is powerful and not easy to master
The most important things we skipped are the techniques Prolog programmers use to get the most out of it$
2/Pbr ` f̙` ` ___` 3f3!>?" dd@,?nKd@
n@
`" n?" dd@ @@``@n?" dd@ @@``PR @ ` `p>>>(
ZDrgֳgֳ ?0
T Click to edit Master title style!
!:
Ttgֳgֳ ?P0p
RClick to edit Master text styles
Second Level
Third Level
Fourth Level
Fifth Level!
S
`ygֳgֳ ?P
>*
`\gֳgֳ ?
@*
`xgֳgֳ ?
@*H
0h? ? f̙ grammars5
@u
(
pF
N
f
6?!
BCqDEF1?p@
BCqDEF1?pp@ N
f
6?
BCaDEF1?`@
BCaDEF1?``@N R
R l
< ?R
BaCPDEF1?O`O`@R
BaCPDEF1?O`@R
Zgֳgֳ ?@/
T Click to edit Master title style!
!
Zgֳgֳ ? ` @
W#Click to edit Master subtitle style$
$
`lgֳgֳ ?
>*
`@gֳgֳ ?
@*
`gֳgֳ ?
@*H
0h? ? f̙
<4p
(
x
c$0
x
c$P0p
0p
4r? eightqueens(X).X = [1/4, 2/2, 3/7, 4/3, 5/6, 6/8, 7/5, 8/1] ;X = [1/5, 2/2, 3/4, 4/7, 5/3, 6/8, 7/6, 8/1] ;s 2''.''/''eH
0h ? f̙rm JSa9
IReRoot EntrydO)PicturesCurrent User,SummaryInformation(
R"#$%&'()*+,./0123456789:;<=>?@ABCDEFGHIJKLM!
owerPoint PresentationPowerPoint PresentationImproved 8Queens SolutionAn ExperimentAnother ExperimentOutlineParts We SkippedA Small LanguageFonts UsedDesign TemplateEmbedded OLE Servers
Slide Titles7
_vejozojozo Jozo Dujmovic