SlideShare a Scribd company logo
1 of 55
1
Prolog - Conclusions
2
Outline
Numeric computation in Prolog
Problem space search
– Knapsack
– 8-queens
Farewell to Prolog
3
Unevaluated Terms
Prolog 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
+(1,*(2,3))
1+ *(2,3)
+(1,2*3)
(1+(2*3))
1+2*3
4
Evaluating Expressions
The 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 operator
?- X is 1+2*3.
X = 7
Yes
5
Instantiation Is Required
?- Y=X+2, X=1.
Y = 1+2
X = 1
Yes
?- Y is X+2, X=1.
ERROR: Arguments are not sufficiently instantiated
?- X=1, Y is X+2.
X = 1
Y = 3
Yes
6
Evaluable Predicates
For 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)
7
Real Values And Integers
?- X is 1/2.
X = 0.5
Yes
?- X is 1.0/2.0.
X = 0.5
Yes
?- X is 2/1.
X = 2
Yes
?- X is 2.0/1.0.
X = 2
Yes
There are two numeric types:
integer and real.
Most of the evaluable
predicates are overloaded for
all combinations.
Prolog is dynamically typed;
the types are used at runtime
to resolve the overloading.
But note that the goal 2=2.0
would fail.
8
Comparisons
Numeric comparison operators:
<, >, =<, >=, =:=, ==
To solve a numeric comparison goal, Prolog
evaluates both sides and compares the
results numerically
So both sides must be fully instantiated
9
Comparisons
?- 1+2 < 1*2.
No
?- 1<2.
Yes
?- 1+2>=1+3.
No
?- X is 1-3, Y is 0-2, X =:= Y.
X = -2
Y = -2
Yes
10
Equalities In Prolog
We 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 instantiated
11
Example: mylength
mylength([],0).
mylength([_|Tail], Len) :-
mylength(Tail, TailLen),
Len is TailLen + 1.
?- mylength([a,b,c],X).
X = 3
Yes
?- mylength(X,3).
X = [_G266, _G269, _G272]
Yes
12
Counterexample: mylength
mylength([],0).
mylength([_|Tail], Len) :-
mylength(Tail, TailLen),
Len = TailLen + 1.
?- mylength([1,2,3,4,5],X).
X = 0+1+1+1+1+1
Yes
13
Example: sum
sum([],0).
sum([Head|Tail],X) :-
sum(Tail,TailSum),
X is Head + TailSum.
?- sum([1,2,3],X).
X = 6
Yes
?- sum([1,2.5,3],X).
X = 6.5
Yes
14
Example: gcd
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).
Note: not just
gcd(X,X,X)
15
The gcd Predicate At Work
?- 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
16
Example: factorial
factorial(X,1) :-
X =:= 1.
factorial(X,Fact) :-
X > 1,
NewX is X - 1,
factorial(NewX,NF),
Fact is X * NF.
?- factorial(5,X).
X = 120
Yes
?- factorial(20,X).
X = 2.4329e+018
Yes
?- factorial(-2,X).
No
17
Outline
Numeric computation in Prolog
Problem space search
– Knapsack
– 8-queens
Farewell to Prolog
18
Problem Space Search
Prolog’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
19
The Knapsack Problem
You are packing for a camping trip
Your pantry contains these items:
Your knapsack holds 4 kg.
What choice <= 4 kg. maximizes calories?
Item Weight in kilograms Calories
bread 4 9200
pasta 2 4600
peanut butter 1 6700
baby food 3 6900
20
Greedy Methods Do Not Work
Most calories first: bread only, 9200
Lightest first: peanut butter + pasta, 11300
(Best choice: peanut butter + baby food,
13600)
Item Weight in kilograms Calories
bread 4 9200
pasta 2 4600
peanut butter 1 6700
baby food 3 6900
21
Search
No algorithm for this problem is known that
– Always gives the best answer, and
– Takes less than exponential time
So brute-force search is nothing to be
ashamed of here
That’s good, since search is something
Prolog does really well
22
Representation
We 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 contents
23
/*
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.
24
/*
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).
A subsequence of a list is a copy of the list
with any number of elements omitted
(Knapsacks are subsequences of the pantry)
25
?- 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
Note 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.
26
/*
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.
27
This decides whether there is a solution that
meets the given calorie goal
Not exactly the answer we want…
?- 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)]
Yes
28
Decision And Optimization
We solved the knapsack decision problem
What we wanted to solve was the knapsack
optimization problem
To do that, we will use another predefined
predicate: findall
29
The 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’s
30
Counting The Solutions
This shows there were four ways of proving
subseq(_,[1,2])
Collected a list of 1’s, one for each proof
?- findall(1,subseq(_,[1,2]),L).
L = [1, 1, 1, 1]
Yes
31
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])
?- findall(subseq(X,[1,2]),subseq(X,[1,2]),L).
X = _G396
L = [subseq([1, 2], [1, 2]), subseq([1], [1, 2]),
subseq([2], [1, 2]), subseq([], [1, 2])]
Yes
32
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]) provable
?- findall(X,subseq(X,[1,2]),L).
X = _G312
L = [[1, 2], [1], [2], []]
Yes
33
/*
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.
34
/*
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).
35
/*
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).
36
?- 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)]
Yes
37
Outline
Numeric computation in Prolog
Problem space search
– Knapsack
– 8-queens
Farewell to Prolog
38
The 8-Queens Problem
Chess background:
– Played on an 8-by-8 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 check
39
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)
40
Example
A chessboard configuration is just a list of
queens
This one is [2/5,3/7,6/1]
8
7
6
5
4
3
2
1
21 43 65 87
Q
Q
Q
41
/*
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(Y1-Y) == abs(X1-X),
nocheck(X/Y, Rest).
42
/*
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).
43
Adequate
This is already enough to solve the
problem: the query legal(X) will find all
legal configurations:
?- legal(X).
X = [] ;
X = [1/1] ;
X = [1/2] ;
X = [1/3]
44
8-Queens Solution
Of course that will take too long: it finds all
64 legal 1-queens solutions, then starts on
the 2-queens solutions, and so on
To make it concentrate right away on
8-queens, we can give a different query:
?- X = [_,_,_,_,_,_,_,_], legal(X).
X = [8/4, 7/2, 6/7, 5/3, 4/6, 3/8, 2/5, 1/1]
Yes
45
Example
Our 8-queens solution
[8/4, 7/2, 6/7, 5/3,
4/6, 3/8, 2/5, 1/1]
8
7
6
5
4
3
2
1
21 43 65 87
Q
Q
Q
Q
Q
Q
Q
Q
46
Room For Improvement
Slow
Finds trivial permutations after the first:
?- 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]
47
An Improvement
Clearly 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
48
/*
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).
49
nocheck(_, []).
nocheck(X/Y, [X1/Y1 | Rest]) :-
% X == X1, assume the X's are distinct
Y == Y1,
abs(Y1-Y) == abs(X1-X),
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).
Since all X-coordinates are already known
to be in range and distinct, these can be
optimized a little
50
Improved 8-Queens Solution
Now much faster
Does not bother with permutations
?- 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] ;
51
An Experiment
Fails: “arguments not sufficiently
instantiated”
The member condition does not just test
in-range coordinates; it generates them
legal([]).
legal([X/Y | Rest]) :-
legal(Rest),
% member(X,[1,2,3,4,5,6,7,8]), assume X in range
1=<Y, Y=<8, % was member(Y,[1,2,3,4,5,6,7,8]),
nocheck(X/Y, Rest).
52
Another Experiment
Fails: “arguments not sufficiently
instantiated”
The legal(Rest) condition must come
first, because it generates the partial
solution tested by nocheck
legal([]).
legal([X/Y | 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),
legal(Rest). % formerly the first condition
53
Outline
Numeric computation in Prolog
Problem space search
– Knapsack
– 8-queens
Farewell to Prolog
54
Parts We Skipped
The cut (!)
– A goal that always succeeds, but only once
– Used to control backtracking
Exception handling
– System-generated or user-generated 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.
55
A Small Language
We 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

More Related Content

What's hot

An Application of Interval Valued Fuzzy Soft Matrix In Medical Diagnosis
An Application of Interval Valued Fuzzy Soft Matrix In Medical DiagnosisAn Application of Interval Valued Fuzzy Soft Matrix In Medical Diagnosis
An Application of Interval Valued Fuzzy Soft Matrix In Medical Diagnosisiosrjce
 
81 systems of linear equations 1
81 systems of linear equations 181 systems of linear equations 1
81 systems of linear equations 1math126
 
Exact Solutions of the Klein-Gordon Equation for the Q-Deformed Morse Potenti...
Exact Solutions of the Klein-Gordon Equation for the Q-Deformed Morse Potenti...Exact Solutions of the Klein-Gordon Equation for the Q-Deformed Morse Potenti...
Exact Solutions of the Klein-Gordon Equation for the Q-Deformed Morse Potenti...ijrap
 
Equation and inequalities
Equation and inequalitiesEquation and inequalities
Equation and inequalitiesRione Drevale
 
Probability based learning (in book: Machine learning for predictve data anal...
Probability based learning (in book: Machine learning for predictve data anal...Probability based learning (in book: Machine learning for predictve data anal...
Probability based learning (in book: Machine learning for predictve data anal...Duyen Do
 
Maximum Likelihood Estimation of Beetle
Maximum Likelihood Estimation of BeetleMaximum Likelihood Estimation of Beetle
Maximum Likelihood Estimation of BeetleLiang Kai Hu
 
Discrete mathematics OR Structure
Discrete mathematics OR Structure Discrete mathematics OR Structure
Discrete mathematics OR Structure Abdullah Jan
 

What's hot (10)

An Application of Interval Valued Fuzzy Soft Matrix In Medical Diagnosis
An Application of Interval Valued Fuzzy Soft Matrix In Medical DiagnosisAn Application of Interval Valued Fuzzy Soft Matrix In Medical Diagnosis
An Application of Interval Valued Fuzzy Soft Matrix In Medical Diagnosis
 
81 systems of linear equations 1
81 systems of linear equations 181 systems of linear equations 1
81 systems of linear equations 1
 
Bird’s-eye view of Gaussian harmonic analysis
Bird’s-eye view of Gaussian harmonic analysisBird’s-eye view of Gaussian harmonic analysis
Bird’s-eye view of Gaussian harmonic analysis
 
1.7
1.71.7
1.7
 
Exact Solutions of the Klein-Gordon Equation for the Q-Deformed Morse Potenti...
Exact Solutions of the Klein-Gordon Equation for the Q-Deformed Morse Potenti...Exact Solutions of the Klein-Gordon Equation for the Q-Deformed Morse Potenti...
Exact Solutions of the Klein-Gordon Equation for the Q-Deformed Morse Potenti...
 
April2012ART_01(1)
April2012ART_01(1)April2012ART_01(1)
April2012ART_01(1)
 
Equation and inequalities
Equation and inequalitiesEquation and inequalities
Equation and inequalities
 
Probability based learning (in book: Machine learning for predictve data anal...
Probability based learning (in book: Machine learning for predictve data anal...Probability based learning (in book: Machine learning for predictve data anal...
Probability based learning (in book: Machine learning for predictve data anal...
 
Maximum Likelihood Estimation of Beetle
Maximum Likelihood Estimation of BeetleMaximum Likelihood Estimation of Beetle
Maximum Likelihood Estimation of Beetle
 
Discrete mathematics OR Structure
Discrete mathematics OR Structure Discrete mathematics OR Structure
Discrete mathematics OR Structure
 

Viewers also liked

Nlp naive bayes
Nlp naive bayesNlp naive bayes
Nlp naive bayesJames Wong
 
Database concepts
Database conceptsDatabase concepts
Database conceptsJames Wong
 
Datamining with nb
Datamining with nbDatamining with nb
Datamining with nbJames Wong
 
Database introduction
Database introductionDatabase introduction
Database introductionHarry Potter
 
Hash& mac algorithms
Hash& mac algorithmsHash& mac algorithms
Hash& mac algorithmsHarry Potter
 
Text categorization as graph
Text categorization as graphText categorization as graph
Text categorization as graphHarry Potter
 
Access data connection
Access data connectionAccess data connection
Access data connectionYoung Alista
 
Key exchange in crypto
Key exchange in cryptoKey exchange in crypto
Key exchange in cryptoYoung Alista
 
Introduction toprolog
Introduction toprologIntroduction toprolog
Introduction toprologYoung Alista
 
Introduction to security_and_crypto
Introduction to security_and_cryptoIntroduction to security_and_crypto
Introduction to security_and_cryptoYoung Alista
 
Crypto theory practice
Crypto theory practiceCrypto theory practice
Crypto theory practiceYoung Alista
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues listsJames Wong
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessingJames Wong
 
Crypto passport authentication
Crypto passport authenticationCrypto passport authentication
Crypto passport authenticationYoung Alista
 
Sql database object
Sql database objectSql database object
Sql database objectJames Wong
 

Viewers also liked (20)

Basic dns-mod
Basic dns-modBasic dns-mod
Basic dns-mod
 
Nlp naive bayes
Nlp naive bayesNlp naive bayes
Nlp naive bayes
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
Datamining with nb
Datamining with nbDatamining with nb
Datamining with nb
 
Xml stylus studio
Xml stylus studioXml stylus studio
Xml stylus studio
 
Naïve bayes
Naïve bayesNaïve bayes
Naïve bayes
 
Database introduction
Database introductionDatabase introduction
Database introduction
 
Hash& mac algorithms
Hash& mac algorithmsHash& mac algorithms
Hash& mac algorithms
 
Text categorization as graph
Text categorization as graphText categorization as graph
Text categorization as graph
 
Access data connection
Access data connectionAccess data connection
Access data connection
 
Key exchange in crypto
Key exchange in cryptoKey exchange in crypto
Key exchange in crypto
 
Introduction toprolog
Introduction toprologIntroduction toprolog
Introduction toprolog
 
Introduction to security_and_crypto
Introduction to security_and_cryptoIntroduction to security_and_crypto
Introduction to security_and_crypto
 
Hash crypto
Hash cryptoHash crypto
Hash crypto
 
Crypto theory practice
Crypto theory practiceCrypto theory practice
Crypto theory practice
 
Overview prolog
Overview prologOverview prolog
Overview prolog
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues lists
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessing
 
Crypto passport authentication
Crypto passport authenticationCrypto passport authentication
Crypto passport authentication
 
Sql database object
Sql database objectSql database object
Sql database object
 

Similar to Prolog resume

Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programingrupali_2bonde
 
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEMMrunal Patil
 
module3_Greedymethod_2022.pdf
module3_Greedymethod_2022.pdfmodule3_Greedymethod_2022.pdf
module3_Greedymethod_2022.pdfShiwani Gupta
 
376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.ppt376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.pptRohitPaul71
 
Presentation of knapsack
Presentation of knapsackPresentation of knapsack
Presentation of knapsackGaurav Dubey
 
AMS_502_13, 14,15,16 (1).pptx
AMS_502_13, 14,15,16 (1).pptxAMS_502_13, 14,15,16 (1).pptx
AMS_502_13, 14,15,16 (1).pptxbhavypatel2228
 
Data structure notes
Data structure notesData structure notes
Data structure notesanujab5
 
The binomial theorem
The binomial theoremThe binomial theorem
The binomial theoremparassini
 
Class-10-Mathematics-Chapter-1-CBSE-NCERT.ppsx
Class-10-Mathematics-Chapter-1-CBSE-NCERT.ppsxClass-10-Mathematics-Chapter-1-CBSE-NCERT.ppsx
Class-10-Mathematics-Chapter-1-CBSE-NCERT.ppsxSoftcare Solution
 
Workshop 4
Workshop 4Workshop 4
Workshop 4eeetq
 
Optimized Classroom Scheduling at LaGrange College
Optimized Classroom Scheduling at LaGrange CollegeOptimized Classroom Scheduling at LaGrange College
Optimized Classroom Scheduling at LaGrange CollegeJon Ernstberger
 
Linear mixed model-writing sample
Linear mixed model-writing sampleLinear mixed model-writing sample
Linear mixed model-writing sampleQingyang Liu
 

Similar to Prolog resume (20)

Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
PMED Opening Workshop - Measurement Error and Precision Medicine - Michael Wa...
PMED Opening Workshop - Measurement Error and Precision Medicine - Michael Wa...PMED Opening Workshop - Measurement Error and Precision Medicine - Michael Wa...
PMED Opening Workshop - Measurement Error and Precision Medicine - Michael Wa...
 
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
 
Tema 8
Tema 8Tema 8
Tema 8
 
0-1 knapsack problem
0-1 knapsack problem0-1 knapsack problem
0-1 knapsack problem
 
module3_Greedymethod_2022.pdf
module3_Greedymethod_2022.pdfmodule3_Greedymethod_2022.pdf
module3_Greedymethod_2022.pdf
 
376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.ppt376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.ppt
 
Presentation of knapsack
Presentation of knapsackPresentation of knapsack
Presentation of knapsack
 
AMS_502_13, 14,15,16 (1).pptx
AMS_502_13, 14,15,16 (1).pptxAMS_502_13, 14,15,16 (1).pptx
AMS_502_13, 14,15,16 (1).pptx
 
Data structure notes
Data structure notesData structure notes
Data structure notes
 
Aed.pptx
Aed.pptxAed.pptx
Aed.pptx
 
Ppt 1.1 and 1.2
Ppt 1.1 and 1.2Ppt 1.1 and 1.2
Ppt 1.1 and 1.2
 
The binomial theorem
The binomial theoremThe binomial theorem
The binomial theorem
 
Class-10-Mathematics-Chapter-1-CBSE-NCERT.ppsx
Class-10-Mathematics-Chapter-1-CBSE-NCERT.ppsxClass-10-Mathematics-Chapter-1-CBSE-NCERT.ppsx
Class-10-Mathematics-Chapter-1-CBSE-NCERT.ppsx
 
Module 3_DAA (2).pptx
Module 3_DAA (2).pptxModule 3_DAA (2).pptx
Module 3_DAA (2).pptx
 
lab program 6.pdf
lab program 6.pdflab program 6.pdf
lab program 6.pdf
 
Workshop 4
Workshop 4Workshop 4
Workshop 4
 
Optimized Classroom Scheduling at LaGrange College
Optimized Classroom Scheduling at LaGrange CollegeOptimized Classroom Scheduling at LaGrange College
Optimized Classroom Scheduling at LaGrange College
 
Math
MathMath
Math
 
Linear mixed model-writing sample
Linear mixed model-writing sampleLinear mixed model-writing sample
Linear mixed model-writing sample
 

More from James Wong

Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtosJames Wong
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningJames Wong
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryJames Wong
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningJames Wong
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksJames Wong
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsJames Wong
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceJames Wong
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesJames Wong
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileJames Wong
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheJames Wong
 
Abstract class
Abstract classAbstract class
Abstract classJames Wong
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisJames Wong
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaJames Wong
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJames Wong
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonJames Wong
 

More from James Wong (20)

Data race
Data raceData race
Data race
 
Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtos
 
Recursion
RecursionRecursion
Recursion
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Object model
Object modelObject model
Object model
 
Abstract class
Abstract classAbstract class
Abstract class
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Inheritance
InheritanceInheritance
Inheritance
 

Recently uploaded

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Recently uploaded (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

Prolog resume

  • 2. 2 Outline Numeric computation in Prolog Problem space search – Knapsack – 8-queens Farewell to Prolog
  • 3. 3 Unevaluated Terms Prolog 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 +(1,*(2,3)) 1+ *(2,3) +(1,2*3) (1+(2*3)) 1+2*3
  • 4. 4 Evaluating Expressions The 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 operator ?- X is 1+2*3. X = 7 Yes
  • 5. 5 Instantiation Is Required ?- Y=X+2, X=1. Y = 1+2 X = 1 Yes ?- Y is X+2, X=1. ERROR: Arguments are not sufficiently instantiated ?- X=1, Y is X+2. X = 1 Y = 3 Yes
  • 6. 6 Evaluable Predicates For 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)
  • 7. 7 Real Values And Integers ?- X is 1/2. X = 0.5 Yes ?- X is 1.0/2.0. X = 0.5 Yes ?- X is 2/1. X = 2 Yes ?- X is 2.0/1.0. X = 2 Yes There are two numeric types: integer and real. Most of the evaluable predicates are overloaded for all combinations. Prolog is dynamically typed; the types are used at runtime to resolve the overloading. But note that the goal 2=2.0 would fail.
  • 8. 8 Comparisons Numeric comparison operators: <, >, =<, >=, =:=, == To solve a numeric comparison goal, Prolog evaluates both sides and compares the results numerically So both sides must be fully instantiated
  • 9. 9 Comparisons ?- 1+2 < 1*2. No ?- 1<2. Yes ?- 1+2>=1+3. No ?- X is 1-3, Y is 0-2, X =:= Y. X = -2 Y = -2 Yes
  • 10. 10 Equalities In Prolog We 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 instantiated
  • 11. 11 Example: mylength mylength([],0). mylength([_|Tail], Len) :- mylength(Tail, TailLen), Len is TailLen + 1. ?- mylength([a,b,c],X). X = 3 Yes ?- mylength(X,3). X = [_G266, _G269, _G272] Yes
  • 12. 12 Counterexample: mylength mylength([],0). mylength([_|Tail], Len) :- mylength(Tail, TailLen), Len = TailLen + 1. ?- mylength([1,2,3,4,5],X). X = 0+1+1+1+1+1 Yes
  • 13. 13 Example: sum sum([],0). sum([Head|Tail],X) :- sum(Tail,TailSum), X is Head + TailSum. ?- sum([1,2,3],X). X = 6 Yes ?- sum([1,2.5,3],X). X = 6.5 Yes
  • 14. 14 Example: gcd 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). Note: not just gcd(X,X,X)
  • 15. 15 The gcd Predicate At Work ?- 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
  • 16. 16 Example: factorial factorial(X,1) :- X =:= 1. factorial(X,Fact) :- X > 1, NewX is X - 1, factorial(NewX,NF), Fact is X * NF. ?- factorial(5,X). X = 120 Yes ?- factorial(20,X). X = 2.4329e+018 Yes ?- factorial(-2,X). No
  • 17. 17 Outline Numeric computation in Prolog Problem space search – Knapsack – 8-queens Farewell to Prolog
  • 18. 18 Problem Space Search Prolog’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
  • 19. 19 The Knapsack Problem You are packing for a camping trip Your pantry contains these items: Your knapsack holds 4 kg. What choice <= 4 kg. maximizes calories? Item Weight in kilograms Calories bread 4 9200 pasta 2 4600 peanut butter 1 6700 baby food 3 6900
  • 20. 20 Greedy Methods Do Not Work Most calories first: bread only, 9200 Lightest first: peanut butter + pasta, 11300 (Best choice: peanut butter + baby food, 13600) Item Weight in kilograms Calories bread 4 9200 pasta 2 4600 peanut butter 1 6700 baby food 3 6900
  • 21. 21 Search No algorithm for this problem is known that – Always gives the best answer, and – Takes less than exponential time So brute-force search is nothing to be ashamed of here That’s good, since search is something Prolog does really well
  • 22. 22 Representation We 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 contents
  • 23. 23 /* 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.
  • 24. 24 /* 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). A subsequence of a list is a copy of the list with any number of elements omitted (Knapsacks are subsequences of the pantry)
  • 25. 25 ?- 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 Note 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.
  • 26. 26 /* 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.
  • 27. 27 This decides whether there is a solution that meets the given calorie goal Not exactly the answer we want… ?- 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)] Yes
  • 28. 28 Decision And Optimization We solved the knapsack decision problem What we wanted to solve was the knapsack optimization problem To do that, we will use another predefined predicate: findall
  • 29. 29 The 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’s
  • 30. 30 Counting The Solutions This shows there were four ways of proving subseq(_,[1,2]) Collected a list of 1’s, one for each proof ?- findall(1,subseq(_,[1,2]),L). L = [1, 1, 1, 1] Yes
  • 31. 31 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]) ?- findall(subseq(X,[1,2]),subseq(X,[1,2]),L). X = _G396 L = [subseq([1, 2], [1, 2]), subseq([1], [1, 2]), subseq([2], [1, 2]), subseq([], [1, 2])] Yes
  • 32. 32 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]) provable ?- findall(X,subseq(X,[1,2]),L). X = _G312 L = [[1, 2], [1], [2], []] Yes
  • 33. 33 /* 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.
  • 34. 34 /* 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).
  • 35. 35 /* 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).
  • 36. 36 ?- 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)] Yes
  • 37. 37 Outline Numeric computation in Prolog Problem space search – Knapsack – 8-queens Farewell to Prolog
  • 38. 38 The 8-Queens Problem Chess background: – Played on an 8-by-8 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 check
  • 39. 39 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)
  • 40. 40 Example A chessboard configuration is just a list of queens This one is [2/5,3/7,6/1] 8 7 6 5 4 3 2 1 21 43 65 87 Q Q Q
  • 41. 41 /* 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(Y1-Y) == abs(X1-X), nocheck(X/Y, Rest).
  • 42. 42 /* 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).
  • 43. 43 Adequate This is already enough to solve the problem: the query legal(X) will find all legal configurations: ?- legal(X). X = [] ; X = [1/1] ; X = [1/2] ; X = [1/3]
  • 44. 44 8-Queens Solution Of course that will take too long: it finds all 64 legal 1-queens solutions, then starts on the 2-queens solutions, and so on To make it concentrate right away on 8-queens, we can give a different query: ?- X = [_,_,_,_,_,_,_,_], legal(X). X = [8/4, 7/2, 6/7, 5/3, 4/6, 3/8, 2/5, 1/1] Yes
  • 45. 45 Example Our 8-queens solution [8/4, 7/2, 6/7, 5/3, 4/6, 3/8, 2/5, 1/1] 8 7 6 5 4 3 2 1 21 43 65 87 Q Q Q Q Q Q Q Q
  • 46. 46 Room For Improvement Slow Finds trivial permutations after the first: ?- 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]
  • 47. 47 An Improvement Clearly 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
  • 48. 48 /* 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).
  • 49. 49 nocheck(_, []). nocheck(X/Y, [X1/Y1 | Rest]) :- % X == X1, assume the X's are distinct Y == Y1, abs(Y1-Y) == abs(X1-X), 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). Since all X-coordinates are already known to be in range and distinct, these can be optimized a little
  • 50. 50 Improved 8-Queens Solution Now much faster Does not bother with permutations ?- 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] ;
  • 51. 51 An Experiment Fails: “arguments not sufficiently instantiated” The member condition does not just test in-range coordinates; it generates them legal([]). legal([X/Y | Rest]) :- legal(Rest), % member(X,[1,2,3,4,5,6,7,8]), assume X in range 1=<Y, Y=<8, % was member(Y,[1,2,3,4,5,6,7,8]), nocheck(X/Y, Rest).
  • 52. 52 Another Experiment Fails: “arguments not sufficiently instantiated” The legal(Rest) condition must come first, because it generates the partial solution tested by nocheck legal([]). legal([X/Y | 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), legal(Rest). % formerly the first condition
  • 53. 53 Outline Numeric computation in Prolog Problem space search – Knapsack – 8-queens Farewell to Prolog
  • 54. 54 Parts We Skipped The cut (!) – A goal that always succeeds, but only once – Used to control backtracking Exception handling – System-generated or user-generated 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.
  • 55. 55 A Small Language We 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