SlideShare a Scribd company logo
Logic Programming
Some "declarative" slides on
logic programming and Prolog.
James Brucker
Introduction to Logic Programming
 Declarative programming describes what is desired
from the program, not how it should be done
 Declarative language: statements of facts and
propositions that must be satisfied by a solution to the
program
real(x). proposition: x is a real number.
x > 0. proposition: x is greater than 0.
Declarative Languages
 what is a "declarative language"?
 give another example (not Prolog) of a declarative
language.
SELECT * FROM COUNTRY WHERE CONTINENT = 'Asia';
Facts, Rules, ...
 What is a proposition?
 What are facts?
 What are rules?
 What is a predicate?
 What is a compound term?
Facts:
fish(salmon).
likes(cat, tuna).
Predicates:
fish, likes
Compound terms:
likes(cat, X), fish(X)
Atoms:
cat, salmon, tuna
Rule:
eats(cat,X)  likes(cat,X), fish(X).
A Really Simple Directed Graph
a
b c
d
(1) edge(a, b).
(2) edge(a, c).
(3) edge(c, d).
(4) path(X, X).
(5) path(X, Y) 
edge(X, N), path(N, Y).
Question: What are the...
 atoms
 facts
 rules
Clausal Form
 Problem: There are too many ways to express
propositions.
 difficult for a machine to parse or understand
 Clausal form: standard form for expressing propositions
n
m A
A
A
B
B
B 





 
 2
1
2
1
Example:
path(X, Y)  edge(X, N)  path(N, Y).
Antecedent
Consequent
Clausal Form Example
Meaning:
if there is an edge from X to N and there a path from N
to Y,
then there is a path from X to Y.
The above is also called a "headed Horn clause".
In Prolog this is written as a proposition or rule:
path(X, Y)  edge(X, N)  path(N, Y).
path(X, Y) :- edge(X, N) , path(N, Y).
Query
 A query or goal is an input proposition that we want
Prolog to "prove" or disprove.
 A query may or may not require that Prolog give us a
value that satisfies the query (instantiation).
1 ?- edge(a,b).
Yes
2 ?- path(c,b).
No
3 ?- path(c,X).
X = c ;
X = d ;
No
Logical Operations on Propositions
 What are the two operations that a logic programming
language performs on propositions to establish a
query?
That is, how does it satisfy a query, such as:
Unification
Unification is a process of finding values of variables
(instantiation) to match terms. Uses facts.
(1-3) edge(a,b). edge(a,c). edge(c,d). (Facts)
(4) path(X,X). (Rule)
(5) path(X,Y) := edge(X,N), path(N,Y). (Rule)
?- path(a,d). This is the query (goal).
Instantiate { X=a, Y=d }, and unify path(a,d) with Rule 5.
After doing this, Prolog must satisfy:
edge(a,N). This is a subgoal.
path(N,d). This is a subgoal.
Unification in plain English
Compare two atoms and see if there is a substitution
which will make them the same.
How can we unify 6 with 5?
Let X := a
Let Y := Z
1. edge(a, b). (Fact)
5. path(X, Y) :- edge(X, N) , path(N, Y).
6. path(a, Z). (Query)
Resolution
Resolution is an inference rule that allows propositions to
be combined.
 Idea: match the consequent (LHS) of one proposition
with the antecedent (RHS term) of another.
).
(
)
(
then
)
(
)
(
If
)
(
)
(
)
(
)
(
2
1
1
2
2
1
2
1
y
Q
y
P
y
Q
y
P
X
Q
X
Q
X
P
X
P




 Examples are in the textbook and tutorials.
Resolution Example
How can we unify 6 with 5?
Let X := a
Let Y := Z
Resolution:
1. edge(a, b). (Fact)
5. path(X, Y) :- edge(X, N) , path(N, Y).
6. path(a, Z). (Query)
Resolution
Resolution is an inference rule that allows propositions to
be combined.
 Idea: match the consequent (LHS) of one proposition
with the antecedent (RHS term) of another.
).
(
)
(
then
)
(
)
(
If
)
(
)
(
)
(
)
(
2
1
1
2
2
1
2
1
y
Q
y
P
y
Q
y
P
X
Q
X
Q
X
P
X
P




 Examples are in the textbook and tutorials.
How to handle failures
 Prolog can work backwards towards the facts using
resolution, instantiation, and unification.
 As it works, Prolog must try each of several choices.
 These choices can be stored as a tree.
?- path(a,d). The goal.
Unify: unify path(a,d)with Rule 5 by instantiate { X=a,Y=d }
Subgoal: edge(a,N).
Instantiate: N=b which is true by Fact 1.
Subgoal: path(b,d).
Unify: path(b,d)with Rule 5: path(b,d) :- edge(b,N),path(N,d)
Failure: can't instantiate edge(b,N) using any propositions.
How to handle failures (2)
 When a solution process fails, Prolog must undo some
of the decisions it has made.
 This is called backtracking.
 same as backtracking you use in recursion.
 Marks a branch of the tree as failed.
How it Works (1)
There are 2 search/execution strategies that can be
used by declarative languages based on a database of
facts.
1. Forward Chaining
2. Backward Chaining
 what are the meanings of these terms?
How it Works (2)
1. Forward Chaining
2. Backward Chaining
 Which strategy does Prolog use?
 Under what circumstances is one strategy more
effective than the other?
Consider two cases:
 large number of rules, small number of facts
 small number of rules, large number of facts
PROLOG: PROgramming in LOGic
The only "logic" programming language in common use.
3 Parts of a Prolog Program
1. A database contains two kinds of information.
 What information is in a database?
2. A command to read or load the database.
 in Scheme you can use load("filename")
 in Prolog use consult('filename')
3. A query or goal to solve.
Ancestors
ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :-
ancestor(X,Z), ancestor(Z,Y).
parent(X,Y) :- mother(X,Y).
parent(X,Y) :- father(X,Y).
father(bill, jill).
mother(jill, sam).
mother(jill, sally).
File: ancestors.pl
Query the Ancestors
?- consult('/pathname/ancestors.pl').
ancestor(bill,sam).
Yes
?- ancestor(bill,X).
X = jill ;
X = sam ;
ERROR: Out of local stack
?- ancestor(X,bob).
ERROR: Out of local stack
Understanding the Problem
 You need to understand how Prolog finds a solution.
ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :-
ancestor(X,Z), ancestor(Z,Y).
parent(X,Y) :- mother(X,Y).
parent(X,Y) :- father(X,Y).
father(bill,jill).
mother(jill,sam).
father(bob,sam).
Depth-first search
causes immediate
recursion
Factorial
factorial(0,1).
factorial(N,N*M) :- factorial(N-1,M).
 The factorial of 0 is 1.
 The factorial of N is N*M if the the factorial of N-1 is M
File: factorial1.pl
?- consult('/path/factorial1.pl').
?- factorial(0,X).
X = 1
Yes
?- factorial(1,Y).
ERROR: Out of global stack
Query Factorial
?- consult('/path/factorial1.pl').
?- factorial(2,2).
No
?- factorial(1,X).
ERROR: Out of global stack
?- 2*3 = 6.
No
?- 2*3 = 2*3.
Yes
Problem: Arithmetic is not performed automatically.
?- 6 is 2*3.
Yes
?- 2*3 is 6.
No
is(6,2*3).
l-value = r-value ?
Arithmetic via Instantiation: is
 "=" simply means comparison for identity.
factorial(N, 1) :- N=0.
 "is" performs instantiation if the left side doesn't have a
value yet.
product(X,Y,Z) :- Z is X*Y.
 this rule can answer the query:
product(3,4,N).
Answer: N = 12.
 but it can't answer:
product(3,Y,12).
is does not mean assignment!
 This always fails: N is N - 1.
% sumto(N, Total): compute Total = 1 + 2 + ... + N.
sumto(N, 0) :- N =< 0.
sumto(N, Total) :=
Total is Subtotal + N,
N is N-1, always fails
sumto(N, Subtotal).
?- sumto(0, Sum).
Sum = 0.
Yes
?- sumto(1, Sum).
No
is : how to fix?
 How would you fix this problem?
% sumto(N, Total): compute Total = 1 + 2 + ... + N.
sumto(N, 0) :- N =< 0.
sumto(N, Total) :=
N1 is N-1, always fails
sumto(N1, Subtotal),
Total is Subtotal + N.
?= sumto(5, X).
Factorial revised
factorial(0,1).
factorial(N,P) :- N1 is N-1,
factorial(N1,M), P is M*N.
Meaning:
 The factorial of 0 is 1.
 factorial of N is P
if N1 = N-1
and factorial of N1 is M
and P is M*N.
File: factorial2.pl
Query Revised Factorial
?- consult('/path/factorial2.pl').
?- factorial(2,2).
Yes
?- factorial(5,X).
X = 120
Yes
?- factorial(5,X).
X = 120 ;
ERROR: Out of local stack
?- factorial(X,120).
but still has some problems...
request another solution
Factorial revised again
factorial(0,1).
factorial(N,P) :- not(N=0), N1 is N-1,
factorial(N1,M), P is M*N.
File: factorial3.pl
?- factorial(5,X).
X = 120 ;
No
?-
Makes the rules mutually exclusive.
Readability: one clause per line
factorial(0,1).
factorial(N,P) :- not(N=0), N1 is N-1,
factorial(N1,M), P is M*N.
factorial(0,1).
factorial(N,P) :-
not(N=0),
N1 is N-1,
factorial(N1,M),
P is M*N.
Better
Finding a Path through a Graph
edge(a, b).
edge(b, c).
edge(b, d).
edge(d, e). edge(d, f).
path(X, X).
path(X, Y) :- edge(X, Z), path(Z, Y).
a
b
c d
e f
?- edge(a, b).
Yes
?- path(a, a).
Yes
?- path(a, e).
Yes
?- path(e, a).
No
How To Define an Undirected Graph?
edge(a, b).
edge(b, c).
edge(b, d).
edge(d, e).
edge(d, f).
edge(X, Y) := not(X=Y), edge(Y, X).
path(X, X).
path(X, Y) :- edge(X, Z), path(Z, Y).
a
b
c d
e f
?- edge(b, a).
Yes
?- path(a, b).
Yes
?- path(b, e).
No
Queries and Answers
 When you issue a query in Prolog, what are the
possible responses from Prolog?
% Suppose "likes" is already in the database
:- likes(jomzaap, 219212). % Programming Languages.
Yes.
:- likes(papon, 403111). % Chemistry.
No.
:- likes(Who, 204219). % Theory of Computing?
Who = pattarin
 Does this mean Papon doesn't like Chemistry?
Closed World Assumption
 What is the Closed World Assumption?
 How does this affect the interpretation of results from
Prolog?
List Processing
 [Head | Tail] works like "car" and "cdr" in Scheme.
 Example:
?- [H | T ] = [a,b,c,d,e].
returns:
H = a
T = [b,c,d,e]
 This can be used to build lists and decompose lists.
 Can use [H|T] on the left side to de/construct a list:
path(X, Y, [X|P]) :-
edge(X, Node),
path(Node, Y, P).
member Predicate
 Test whether something is a member of a list
?- member(a, [b,c,d]).
No.
 can be used to have Prolog try all values of a list as
values of a variable.
?- member(X, [a1,b2,c3,d4] ).
X = a1
X = b2
X = c3
member Predicate example
 Use member to try all values of a list.
 Useful for problems like
 Queen safety
 enumerating possible rows and columns in a game.
% dumb function to find square root of 9
squareroot9(N) :-
member(N,[1,2,3,4,5,5,6,7,8,9]),
9 is N*N.
appending Lists
?- append([a,b],[c,d,e],L).
L = [a,b,c,d,e]
 append can resolve other parameters, too:
?- append(X, [b,c,d], [a,b,c,d] ).
X = a
?- append([],[a,b,c],L).
L = [a,b,c]
Defining your own 'append'
append([], List, List).
append([Head|Tail], X, [Head|NewTail]) :-
append(Tail, X, NewTail).
Type Determination
 Prolog is a weakly typed language.
 It provides propositions for testing the type of a variable
PREDICATE SATISFIED (TRUE) IF
var(X) X is a variable
nonvar(X) X is not a variable
atom(A) A is an atom
integer(K) K is an integer
real(R) R is a floating point number
number(N) N is an integer or real
atomic(A) A is an atom or a number or a string
functor(T,F,A) T is a term with functor F, arity A
T =..L T is a term, L is a list.
clause(H,T) H :- T is a rule in the program
Tracing the Solution
?- trace.
[trace] ?- path(a,d).
Call: (8) path(a, d) ? creep
Call: (9) edge(a, _L169) ? creep
Exit: (9) edge(a, b) ? creep
Call: (9) path(b, d) ? creep
Call: (10) edge(b, _L204) ? creep
Exit: (10) edge(b, c) ? creep
Call: (10) path(c, d) ? creep
Call: (11) edge(c, _L239) ? creep
^ Call: (12) not(c=_G471) ? creep
^ Fail: (12) not(c=_G471) ? creep
Fail: (11) edge(c, _L239) ? creep
Fail: (10) path(c, d) ? creep
Redo: (10) edge(b, _L204) ? creep
Solution Process
Stack Substitution (Instantiation)
[path(a,c), path(X,X)]
[path(a,c), path(a,a)] X = a
Undo.
[path(a,c), path(X,X)]
[path(a,c), path(c,c)] X = c
Undo.
(1) path(X,X).
(2) path(X,Y) := edge(X,Z), path(Z,Y).
?- path(a,c).
Solution Process (2)
Stack Substitution (Instantiation)
[path(a,c), path(X,Y)] (Rule 2)
[path(a,c), path(a,Y)] X = a
X = a, Y = c
edge(a,Z), path(Z,c) new subgoals
edge(a,b), path(b,c) X = a, Y = c, Z = b
path(b,c) edge(a,b) is a fact - pop it.
(1) path(X,X).
(2) path(X,Y) := edge(X,Z), path(Z,Y).
?- path(a,c).
What does this do?
% what does this do?
sub([], List).
sub([H|T], List) :-
member(H, List),
sub(T, List).
What does this do?
% what does this do?
foo([], _, []).
foo([H|T], List, [H|P]) :-
member(H, List),
foo(T, List, P).
foo([H|T], List, P) :-
not( member(H, List) ),
foo(T, List, P).
Underscore (_) means "don't care".
It accepts any value.
Max Function
 Write a Prolog program to find the max of a list of
numbers:
 max( List, X).
 max( [3, 5, 8, -4, 6], X).
X = 8.
 Strategy:
 use recursion
 divide the list into a Head and Tail.
 compare X to Head and Tail. Two cases:
 Head = max( Tail ). in this case answer is X is Head.
 X = max( Tail ) and Head < X.
 what is the base case?
Max Function
% max(List, X) : X is max of List members
max([X], X). base case
max([H|Tail], H) :- 1st element is max
max(Tail, X),
H >= X.
max([H|Tail], X) :- 1st element not max
complete this
case.
Towers of Hanoi
% Move one disk
move(1,From,To,_) :-
write('Move top disk from '),
write(From),
write(' to '),
write(To),
nl.
% Move more than one disk.
move(N,From,To,Other) :-
N>1,
M is N-1,
move(M,From,Other,To),
move(1,From,To,_),
move(M,Other,To,From).
See tutorials at:
www.csupomona.edu and
www.cse.ucsc.edu
Learning Prolog
 The Textbook - good explanation of concepts
 Tutorials:
 http://www.thefreecountry.com/documentation/onlineprolog.sht
ml has annotated links to tutorials.
 http://www.cse.ucsc.edu/classes/cmps112/Spring03/languages
/prolog/PrologIntro.pdf last section explains how Prolog
resolves queries using a stack and list of substitutions.
 http://cs.wwc.edu/~cs_dept/KU/PR/Prolog.html explains
Prolog syntax and semantics.
 http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/conte
nts.html has many examples

More Related Content

What's hot

Category Theory in 10 Minutes
Category Theory in 10 MinutesCategory Theory in 10 Minutes
Category Theory in 10 Minutes
Jordan Parmer
 
Knowledge Extraction
Knowledge ExtractionKnowledge Extraction
Knowledge Extraction
Pierre de Lacaze
 
Static name resolution
Static name resolutionStatic name resolution
Static name resolution
Eelco Visser
 
Invitation to Scala
Invitation to ScalaInvitation to Scala
Invitation to Scala
Michael Bar-Sinai
 
Dynamic Semantics
Dynamic SemanticsDynamic Semantics
Dynamic Semantics
Eelco Visser
 
Declare Your Language: Name Resolution
Declare Your Language: Name ResolutionDeclare Your Language: Name Resolution
Declare Your Language: Name Resolution
Eelco Visser
 
Lexical Analysis
Lexical AnalysisLexical Analysis
Lexical Analysis
Eelco Visser
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term Rewriting
Eelco Visser
 
Term Rewriting
Term RewritingTerm Rewriting
Term Rewriting
Eelco Visser
 
Static Analysis
Static AnalysisStatic Analysis
Static Analysis
Eelco Visser
 
Introduction to Category Theory for software engineers
Introduction to Category Theory for software engineersIntroduction to Category Theory for software engineers
Introduction to Category Theory for software engineers
Pranav Prakash
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginners
kenbot
 
Regular expression
Regular expressionRegular expression
Regular expression
Rajon
 
Declare Your Language: Type Checking
Declare Your Language: Type CheckingDeclare Your Language: Type Checking
Declare Your Language: Type Checking
Eelco Visser
 
Types and perl language
Types and perl languageTypes and perl language
Types and perl language
Masahiro Honma
 
Declarative Semantics Definition - Term Rewriting
Declarative Semantics Definition - Term RewritingDeclarative Semantics Definition - Term Rewriting
Declarative Semantics Definition - Term Rewriting
Guido Wachsmuth
 
Introduction - Imperative and Object-Oriented Languages
Introduction - Imperative and Object-Oriented LanguagesIntroduction - Imperative and Object-Oriented Languages
Introduction - Imperative and Object-Oriented Languages
Guido Wachsmuth
 
Minimizing DFA
Minimizing DFAMinimizing DFA
Minimizing DFA
Animesh Chaturvedi
 

What's hot (20)

Category Theory in 10 Minutes
Category Theory in 10 MinutesCategory Theory in 10 Minutes
Category Theory in 10 Minutes
 
Knowledge Extraction
Knowledge ExtractionKnowledge Extraction
Knowledge Extraction
 
Pl vol1
Pl vol1Pl vol1
Pl vol1
 
Static name resolution
Static name resolutionStatic name resolution
Static name resolution
 
Invitation to Scala
Invitation to ScalaInvitation to Scala
Invitation to Scala
 
Dynamic Semantics
Dynamic SemanticsDynamic Semantics
Dynamic Semantics
 
Declare Your Language: Name Resolution
Declare Your Language: Name ResolutionDeclare Your Language: Name Resolution
Declare Your Language: Name Resolution
 
Lexical Analysis
Lexical AnalysisLexical Analysis
Lexical Analysis
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term Rewriting
 
Term Rewriting
Term RewritingTerm Rewriting
Term Rewriting
 
Static Analysis
Static AnalysisStatic Analysis
Static Analysis
 
Introduction to Category Theory for software engineers
Introduction to Category Theory for software engineersIntroduction to Category Theory for software engineers
Introduction to Category Theory for software engineers
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginners
 
Regular expression
Regular expressionRegular expression
Regular expression
 
Declare Your Language: Type Checking
Declare Your Language: Type CheckingDeclare Your Language: Type Checking
Declare Your Language: Type Checking
 
Types and perl language
Types and perl languageTypes and perl language
Types and perl language
 
Declarative Semantics Definition - Term Rewriting
Declarative Semantics Definition - Term RewritingDeclarative Semantics Definition - Term Rewriting
Declarative Semantics Definition - Term Rewriting
 
Introduction - Imperative and Object-Oriented Languages
Introduction - Imperative and Object-Oriented LanguagesIntroduction - Imperative and Object-Oriented Languages
Introduction - Imperative and Object-Oriented Languages
 
Minimizing DFA
Minimizing DFAMinimizing DFA
Minimizing DFA
 

Similar to 09 logic programming

Efficient end-to-end learning for quantizable representations
Efficient end-to-end learning for quantizable representationsEfficient end-to-end learning for quantizable representations
Efficient end-to-end learning for quantizable representations
NAVER Engineering
 
Q-Metrics in Theory And Practice
Q-Metrics in Theory And PracticeQ-Metrics in Theory And Practice
Q-Metrics in Theory And Practice
guest3550292
 
Q-Metrics in Theory and Practice
Q-Metrics in Theory and PracticeQ-Metrics in Theory and Practice
Q-Metrics in Theory and Practice
Magdi Mohamed
 
Automatic bayesian cubature
Automatic bayesian cubatureAutomatic bayesian cubature
Automatic bayesian cubature
Jagadeeswaran Rathinavel
 
ISI MSQE Entrance Question Paper (2008)
ISI MSQE Entrance Question Paper (2008)ISI MSQE Entrance Question Paper (2008)
ISI MSQE Entrance Question Paper (2008)
CrackDSE
 
Declarative Datalog Debugging for Mere Mortals
Declarative Datalog Debugging for Mere MortalsDeclarative Datalog Debugging for Mere Mortals
Declarative Datalog Debugging for Mere Mortals
Bertram Ludäscher
 
matlab lecture 4 solving mathematical problems.ppt
matlab lecture 4 solving mathematical problems.pptmatlab lecture 4 solving mathematical problems.ppt
matlab lecture 4 solving mathematical problems.ppt
aaaaboud1
 
Applied machine learning for search engine relevance 3
Applied machine learning for search engine relevance 3Applied machine learning for search engine relevance 3
Applied machine learning for search engine relevance 3
Charles Martin
 
TR tabling presentation_2010_09
TR tabling presentation_2010_09TR tabling presentation_2010_09
TR tabling presentation_2010_09
Paul Fodor
 
Fosdem 2013 petra selmer flexible querying of graph data
Fosdem 2013 petra selmer   flexible querying of graph dataFosdem 2013 petra selmer   flexible querying of graph data
Fosdem 2013 petra selmer flexible querying of graph data
Petra Selmer
 
Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...
Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...
Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...
The Statistical and Applied Mathematical Sciences Institute
 
Truth, deduction, computation lecture g
Truth, deduction, computation   lecture gTruth, deduction, computation   lecture g
Truth, deduction, computation lecture g
Vlad Patryshev
 
Pl vol1
Pl vol1Pl vol1
Pl vol1
Aarsh Ps
 
Divergence clustering
Divergence clusteringDivergence clustering
Divergence clustering
Frank Nielsen
 
Tensor Train data format for uncertainty quantification
Tensor Train data format for uncertainty quantificationTensor Train data format for uncertainty quantification
Tensor Train data format for uncertainty quantification
Alexander Litvinenko
 
Introduction
IntroductionIntroduction
Introductionbutest
 
Higher-order Factorization Machines(第5回ステアラボ人工知能セミナー)
Higher-order Factorization Machines(第5回ステアラボ人工知能セミナー)Higher-order Factorization Machines(第5回ステアラボ人工知能セミナー)
Higher-order Factorization Machines(第5回ステアラボ人工知能セミナー)
STAIR Lab, Chiba Institute of Technology
 

Similar to 09 logic programming (20)

Efficient end-to-end learning for quantizable representations
Efficient end-to-end learning for quantizable representationsEfficient end-to-end learning for quantizable representations
Efficient end-to-end learning for quantizable representations
 
Q-Metrics in Theory And Practice
Q-Metrics in Theory And PracticeQ-Metrics in Theory And Practice
Q-Metrics in Theory And Practice
 
Q-Metrics in Theory and Practice
Q-Metrics in Theory and PracticeQ-Metrics in Theory and Practice
Q-Metrics in Theory and Practice
 
Automatic bayesian cubature
Automatic bayesian cubatureAutomatic bayesian cubature
Automatic bayesian cubature
 
ISI MSQE Entrance Question Paper (2008)
ISI MSQE Entrance Question Paper (2008)ISI MSQE Entrance Question Paper (2008)
ISI MSQE Entrance Question Paper (2008)
 
Declarative Datalog Debugging for Mere Mortals
Declarative Datalog Debugging for Mere MortalsDeclarative Datalog Debugging for Mere Mortals
Declarative Datalog Debugging for Mere Mortals
 
matlab lecture 4 solving mathematical problems.ppt
matlab lecture 4 solving mathematical problems.pptmatlab lecture 4 solving mathematical problems.ppt
matlab lecture 4 solving mathematical problems.ppt
 
Applied machine learning for search engine relevance 3
Applied machine learning for search engine relevance 3Applied machine learning for search engine relevance 3
Applied machine learning for search engine relevance 3
 
TR tabling presentation_2010_09
TR tabling presentation_2010_09TR tabling presentation_2010_09
TR tabling presentation_2010_09
 
Fosdem 2013 petra selmer flexible querying of graph data
Fosdem 2013 petra selmer   flexible querying of graph dataFosdem 2013 petra selmer   flexible querying of graph data
Fosdem 2013 petra selmer flexible querying of graph data
 
Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...
Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...
Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...
 
Truth, deduction, computation lecture g
Truth, deduction, computation   lecture gTruth, deduction, computation   lecture g
Truth, deduction, computation lecture g
 
cswiercz-general-presentation
cswiercz-general-presentationcswiercz-general-presentation
cswiercz-general-presentation
 
Pl vol1
Pl vol1Pl vol1
Pl vol1
 
Divergence clustering
Divergence clusteringDivergence clustering
Divergence clustering
 
Tensor Train data format for uncertainty quantification
Tensor Train data format for uncertainty quantificationTensor Train data format for uncertainty quantification
Tensor Train data format for uncertainty quantification
 
Introduction
IntroductionIntroduction
Introduction
 
www.ijerd.com
www.ijerd.comwww.ijerd.com
www.ijerd.com
 
Higher-order Factorization Machines(第5回ステアラボ人工知能セミナー)
Higher-order Factorization Machines(第5回ステアラボ人工知能セミナー)Higher-order Factorization Machines(第5回ステアラボ人工知能セミナー)
Higher-order Factorization Machines(第5回ステアラボ人工知能セミナー)
 
Functions
FunctionsFunctions
Functions
 

Recently uploaded

Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
veerababupersonal22
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 

Recently uploaded (20)

Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 

09 logic programming

  • 1. Logic Programming Some "declarative" slides on logic programming and Prolog. James Brucker
  • 2. Introduction to Logic Programming  Declarative programming describes what is desired from the program, not how it should be done  Declarative language: statements of facts and propositions that must be satisfied by a solution to the program real(x). proposition: x is a real number. x > 0. proposition: x is greater than 0.
  • 3. Declarative Languages  what is a "declarative language"?  give another example (not Prolog) of a declarative language. SELECT * FROM COUNTRY WHERE CONTINENT = 'Asia';
  • 4. Facts, Rules, ...  What is a proposition?  What are facts?  What are rules?  What is a predicate?  What is a compound term?
  • 5. Facts: fish(salmon). likes(cat, tuna). Predicates: fish, likes Compound terms: likes(cat, X), fish(X) Atoms: cat, salmon, tuna Rule: eats(cat,X)  likes(cat,X), fish(X).
  • 6. A Really Simple Directed Graph a b c d (1) edge(a, b). (2) edge(a, c). (3) edge(c, d). (4) path(X, X). (5) path(X, Y)  edge(X, N), path(N, Y). Question: What are the...  atoms  facts  rules
  • 7. Clausal Form  Problem: There are too many ways to express propositions.  difficult for a machine to parse or understand  Clausal form: standard form for expressing propositions n m A A A B B B          2 1 2 1 Example: path(X, Y)  edge(X, N)  path(N, Y). Antecedent Consequent
  • 8. Clausal Form Example Meaning: if there is an edge from X to N and there a path from N to Y, then there is a path from X to Y. The above is also called a "headed Horn clause". In Prolog this is written as a proposition or rule: path(X, Y)  edge(X, N)  path(N, Y). path(X, Y) :- edge(X, N) , path(N, Y).
  • 9. Query  A query or goal is an input proposition that we want Prolog to "prove" or disprove.  A query may or may not require that Prolog give us a value that satisfies the query (instantiation). 1 ?- edge(a,b). Yes 2 ?- path(c,b). No 3 ?- path(c,X). X = c ; X = d ; No
  • 10. Logical Operations on Propositions  What are the two operations that a logic programming language performs on propositions to establish a query? That is, how does it satisfy a query, such as:
  • 11. Unification Unification is a process of finding values of variables (instantiation) to match terms. Uses facts. (1-3) edge(a,b). edge(a,c). edge(c,d). (Facts) (4) path(X,X). (Rule) (5) path(X,Y) := edge(X,N), path(N,Y). (Rule) ?- path(a,d). This is the query (goal). Instantiate { X=a, Y=d }, and unify path(a,d) with Rule 5. After doing this, Prolog must satisfy: edge(a,N). This is a subgoal. path(N,d). This is a subgoal.
  • 12. Unification in plain English Compare two atoms and see if there is a substitution which will make them the same. How can we unify 6 with 5? Let X := a Let Y := Z 1. edge(a, b). (Fact) 5. path(X, Y) :- edge(X, N) , path(N, Y). 6. path(a, Z). (Query)
  • 13. Resolution Resolution is an inference rule that allows propositions to be combined.  Idea: match the consequent (LHS) of one proposition with the antecedent (RHS term) of another. ). ( ) ( then ) ( ) ( If ) ( ) ( ) ( ) ( 2 1 1 2 2 1 2 1 y Q y P y Q y P X Q X Q X P X P      Examples are in the textbook and tutorials.
  • 14. Resolution Example How can we unify 6 with 5? Let X := a Let Y := Z Resolution: 1. edge(a, b). (Fact) 5. path(X, Y) :- edge(X, N) , path(N, Y). 6. path(a, Z). (Query)
  • 15. Resolution Resolution is an inference rule that allows propositions to be combined.  Idea: match the consequent (LHS) of one proposition with the antecedent (RHS term) of another. ). ( ) ( then ) ( ) ( If ) ( ) ( ) ( ) ( 2 1 1 2 2 1 2 1 y Q y P y Q y P X Q X Q X P X P      Examples are in the textbook and tutorials.
  • 16. How to handle failures  Prolog can work backwards towards the facts using resolution, instantiation, and unification.  As it works, Prolog must try each of several choices.  These choices can be stored as a tree. ?- path(a,d). The goal. Unify: unify path(a,d)with Rule 5 by instantiate { X=a,Y=d } Subgoal: edge(a,N). Instantiate: N=b which is true by Fact 1. Subgoal: path(b,d). Unify: path(b,d)with Rule 5: path(b,d) :- edge(b,N),path(N,d) Failure: can't instantiate edge(b,N) using any propositions.
  • 17. How to handle failures (2)  When a solution process fails, Prolog must undo some of the decisions it has made.  This is called backtracking.  same as backtracking you use in recursion.  Marks a branch of the tree as failed.
  • 18. How it Works (1) There are 2 search/execution strategies that can be used by declarative languages based on a database of facts. 1. Forward Chaining 2. Backward Chaining  what are the meanings of these terms?
  • 19. How it Works (2) 1. Forward Chaining 2. Backward Chaining  Which strategy does Prolog use?  Under what circumstances is one strategy more effective than the other? Consider two cases:  large number of rules, small number of facts  small number of rules, large number of facts
  • 20. PROLOG: PROgramming in LOGic The only "logic" programming language in common use.
  • 21. 3 Parts of a Prolog Program 1. A database contains two kinds of information.  What information is in a database? 2. A command to read or load the database.  in Scheme you can use load("filename")  in Prolog use consult('filename') 3. A query or goal to solve.
  • 22. Ancestors ancestor(X,Y) :- parent(X,Y). ancestor(X,Y) :- ancestor(X,Z), ancestor(Z,Y). parent(X,Y) :- mother(X,Y). parent(X,Y) :- father(X,Y). father(bill, jill). mother(jill, sam). mother(jill, sally). File: ancestors.pl
  • 23. Query the Ancestors ?- consult('/pathname/ancestors.pl'). ancestor(bill,sam). Yes ?- ancestor(bill,X). X = jill ; X = sam ; ERROR: Out of local stack ?- ancestor(X,bob). ERROR: Out of local stack
  • 24. Understanding the Problem  You need to understand how Prolog finds a solution. ancestor(X,Y) :- parent(X,Y). ancestor(X,Y) :- ancestor(X,Z), ancestor(Z,Y). parent(X,Y) :- mother(X,Y). parent(X,Y) :- father(X,Y). father(bill,jill). mother(jill,sam). father(bob,sam). Depth-first search causes immediate recursion
  • 25. Factorial factorial(0,1). factorial(N,N*M) :- factorial(N-1,M).  The factorial of 0 is 1.  The factorial of N is N*M if the the factorial of N-1 is M File: factorial1.pl ?- consult('/path/factorial1.pl'). ?- factorial(0,X). X = 1 Yes ?- factorial(1,Y). ERROR: Out of global stack
  • 26. Query Factorial ?- consult('/path/factorial1.pl'). ?- factorial(2,2). No ?- factorial(1,X). ERROR: Out of global stack ?- 2*3 = 6. No ?- 2*3 = 2*3. Yes Problem: Arithmetic is not performed automatically. ?- 6 is 2*3. Yes ?- 2*3 is 6. No is(6,2*3). l-value = r-value ?
  • 27. Arithmetic via Instantiation: is  "=" simply means comparison for identity. factorial(N, 1) :- N=0.  "is" performs instantiation if the left side doesn't have a value yet. product(X,Y,Z) :- Z is X*Y.  this rule can answer the query: product(3,4,N). Answer: N = 12.  but it can't answer: product(3,Y,12).
  • 28. is does not mean assignment!  This always fails: N is N - 1. % sumto(N, Total): compute Total = 1 + 2 + ... + N. sumto(N, 0) :- N =< 0. sumto(N, Total) := Total is Subtotal + N, N is N-1, always fails sumto(N, Subtotal). ?- sumto(0, Sum). Sum = 0. Yes ?- sumto(1, Sum). No
  • 29. is : how to fix?  How would you fix this problem? % sumto(N, Total): compute Total = 1 + 2 + ... + N. sumto(N, 0) :- N =< 0. sumto(N, Total) := N1 is N-1, always fails sumto(N1, Subtotal), Total is Subtotal + N. ?= sumto(5, X).
  • 30. Factorial revised factorial(0,1). factorial(N,P) :- N1 is N-1, factorial(N1,M), P is M*N. Meaning:  The factorial of 0 is 1.  factorial of N is P if N1 = N-1 and factorial of N1 is M and P is M*N. File: factorial2.pl
  • 31. Query Revised Factorial ?- consult('/path/factorial2.pl'). ?- factorial(2,2). Yes ?- factorial(5,X). X = 120 Yes ?- factorial(5,X). X = 120 ; ERROR: Out of local stack ?- factorial(X,120). but still has some problems... request another solution
  • 32. Factorial revised again factorial(0,1). factorial(N,P) :- not(N=0), N1 is N-1, factorial(N1,M), P is M*N. File: factorial3.pl ?- factorial(5,X). X = 120 ; No ?- Makes the rules mutually exclusive.
  • 33. Readability: one clause per line factorial(0,1). factorial(N,P) :- not(N=0), N1 is N-1, factorial(N1,M), P is M*N. factorial(0,1). factorial(N,P) :- not(N=0), N1 is N-1, factorial(N1,M), P is M*N. Better
  • 34. Finding a Path through a Graph edge(a, b). edge(b, c). edge(b, d). edge(d, e). edge(d, f). path(X, X). path(X, Y) :- edge(X, Z), path(Z, Y). a b c d e f ?- edge(a, b). Yes ?- path(a, a). Yes ?- path(a, e). Yes ?- path(e, a). No
  • 35. How To Define an Undirected Graph? edge(a, b). edge(b, c). edge(b, d). edge(d, e). edge(d, f). edge(X, Y) := not(X=Y), edge(Y, X). path(X, X). path(X, Y) :- edge(X, Z), path(Z, Y). a b c d e f ?- edge(b, a). Yes ?- path(a, b). Yes ?- path(b, e). No
  • 36. Queries and Answers  When you issue a query in Prolog, what are the possible responses from Prolog? % Suppose "likes" is already in the database :- likes(jomzaap, 219212). % Programming Languages. Yes. :- likes(papon, 403111). % Chemistry. No. :- likes(Who, 204219). % Theory of Computing? Who = pattarin  Does this mean Papon doesn't like Chemistry?
  • 37. Closed World Assumption  What is the Closed World Assumption?  How does this affect the interpretation of results from Prolog?
  • 38. List Processing  [Head | Tail] works like "car" and "cdr" in Scheme.  Example: ?- [H | T ] = [a,b,c,d,e]. returns: H = a T = [b,c,d,e]  This can be used to build lists and decompose lists.  Can use [H|T] on the left side to de/construct a list: path(X, Y, [X|P]) :- edge(X, Node), path(Node, Y, P).
  • 39. member Predicate  Test whether something is a member of a list ?- member(a, [b,c,d]). No.  can be used to have Prolog try all values of a list as values of a variable. ?- member(X, [a1,b2,c3,d4] ). X = a1 X = b2 X = c3
  • 40. member Predicate example  Use member to try all values of a list.  Useful for problems like  Queen safety  enumerating possible rows and columns in a game. % dumb function to find square root of 9 squareroot9(N) :- member(N,[1,2,3,4,5,5,6,7,8,9]), 9 is N*N.
  • 41. appending Lists ?- append([a,b],[c,d,e],L). L = [a,b,c,d,e]  append can resolve other parameters, too: ?- append(X, [b,c,d], [a,b,c,d] ). X = a ?- append([],[a,b,c],L). L = [a,b,c]
  • 42. Defining your own 'append' append([], List, List). append([Head|Tail], X, [Head|NewTail]) :- append(Tail, X, NewTail).
  • 43. Type Determination  Prolog is a weakly typed language.  It provides propositions for testing the type of a variable PREDICATE SATISFIED (TRUE) IF var(X) X is a variable nonvar(X) X is not a variable atom(A) A is an atom integer(K) K is an integer real(R) R is a floating point number number(N) N is an integer or real atomic(A) A is an atom or a number or a string functor(T,F,A) T is a term with functor F, arity A T =..L T is a term, L is a list. clause(H,T) H :- T is a rule in the program
  • 44. Tracing the Solution ?- trace. [trace] ?- path(a,d). Call: (8) path(a, d) ? creep Call: (9) edge(a, _L169) ? creep Exit: (9) edge(a, b) ? creep Call: (9) path(b, d) ? creep Call: (10) edge(b, _L204) ? creep Exit: (10) edge(b, c) ? creep Call: (10) path(c, d) ? creep Call: (11) edge(c, _L239) ? creep ^ Call: (12) not(c=_G471) ? creep ^ Fail: (12) not(c=_G471) ? creep Fail: (11) edge(c, _L239) ? creep Fail: (10) path(c, d) ? creep Redo: (10) edge(b, _L204) ? creep
  • 45. Solution Process Stack Substitution (Instantiation) [path(a,c), path(X,X)] [path(a,c), path(a,a)] X = a Undo. [path(a,c), path(X,X)] [path(a,c), path(c,c)] X = c Undo. (1) path(X,X). (2) path(X,Y) := edge(X,Z), path(Z,Y). ?- path(a,c).
  • 46. Solution Process (2) Stack Substitution (Instantiation) [path(a,c), path(X,Y)] (Rule 2) [path(a,c), path(a,Y)] X = a X = a, Y = c edge(a,Z), path(Z,c) new subgoals edge(a,b), path(b,c) X = a, Y = c, Z = b path(b,c) edge(a,b) is a fact - pop it. (1) path(X,X). (2) path(X,Y) := edge(X,Z), path(Z,Y). ?- path(a,c).
  • 47. What does this do? % what does this do? sub([], List). sub([H|T], List) :- member(H, List), sub(T, List).
  • 48. What does this do? % what does this do? foo([], _, []). foo([H|T], List, [H|P]) :- member(H, List), foo(T, List, P). foo([H|T], List, P) :- not( member(H, List) ), foo(T, List, P). Underscore (_) means "don't care". It accepts any value.
  • 49. Max Function  Write a Prolog program to find the max of a list of numbers:  max( List, X).  max( [3, 5, 8, -4, 6], X). X = 8.  Strategy:  use recursion  divide the list into a Head and Tail.  compare X to Head and Tail. Two cases:  Head = max( Tail ). in this case answer is X is Head.  X = max( Tail ) and Head < X.  what is the base case?
  • 50. Max Function % max(List, X) : X is max of List members max([X], X). base case max([H|Tail], H) :- 1st element is max max(Tail, X), H >= X. max([H|Tail], X) :- 1st element not max complete this case.
  • 51. Towers of Hanoi % Move one disk move(1,From,To,_) :- write('Move top disk from '), write(From), write(' to '), write(To), nl. % Move more than one disk. move(N,From,To,Other) :- N>1, M is N-1, move(M,From,Other,To), move(1,From,To,_), move(M,Other,To,From). See tutorials at: www.csupomona.edu and www.cse.ucsc.edu
  • 52. Learning Prolog  The Textbook - good explanation of concepts  Tutorials:  http://www.thefreecountry.com/documentation/onlineprolog.sht ml has annotated links to tutorials.  http://www.cse.ucsc.edu/classes/cmps112/Spring03/languages /prolog/PrologIntro.pdf last section explains how Prolog resolves queries using a stack and list of substitutions.  http://cs.wwc.edu/~cs_dept/KU/PR/Prolog.html explains Prolog syntax and semantics.  http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/conte nts.html has many examples