SlideShare a Scribd company logo
1 of 61
Prolog Programming
2
Prolog ProgrammingProlog Programming
 DATA STRUCTURES IN PROLOG
 PROGRAMMING TECHNIQUES
 CONTROL IN PROLOG
 CUTS
3
DATA STRUCTURES IN
PROLOG
 Lists in Prolog
List notation is a way of writing terms
 Terms as Data
Term correspond with list
4
Lists in Prolog
 The simplest way of writing a list is to
enumerate its elements.
The list consisting of the 3 atoms a, b and c can be
written as
[a, b, c]
The list that doesn’t have elements called empty
list denoted as [ ]
5
Lists in Prolog
 We can also specify an initial sequence of
elements and a trailing list, separated by |
The list [a, b, c] can also be written as
[a, b, c | [ ] ]
[a, b | [c] ]
[a | [b, c] ]
6
Lists : Head & Tail
 A special case of this notation is a list with
head H and tail T, written as [H|T]
 The head is the first element of a list, and
 The tail is the list consisting of the remaining
elements.
The list [a, b, c] can also be separated as
• Head:The first element is a
• Tail:The list of remaining elements = [b, c]
7
Lists : Unification
 Unification can be used to extract the
components of a list, so explicit operators for
extracting the head and tail are not needed.
The solution of the query
 Bind variable H to the head and variable T to
the tail of list [a, b, c].
?- [H | T] = [a, b, c].
H = a
T = [b, c]
8
Lists : Specified terms
 The query (partially specified terms)
 The term [ a | T ] is a partial specification of a
list with head a and unknown tail denoted by
variable T.
 Similarly, [ H, b, c] is a partial specification of a
list with unknown head H and tail [b, c].
 These two specification to unify H = a, T =[b,c]
?- [a | T] = [H, b, c].
T = [b, c]
H = a
9
Lists in Prolog
 Example 2 The append relation on lists is
defined by the following rules:
Append([ ], Y, Y).
Append([H | X], Y, [H | Z]) :- append(X,Y,Z).
In words,
The result of appending the empty list [ ] and a list Y is Y.
If the result of appending X and Y is Z, then
the result of appending [H | X] and Y is [H | Z]
10
Lists : Compute Arguments
 The rules for append can be used to compute
any one of the arguments from the other two:
 Inconsistent arguments are rejected
?- append([a, b], [c, d], Z).
Z = [a, b, c, d]
?- append([a, b], Y, [a, b, c, d]).
Y = [c, d]
?- append(X, [c, d], [a, b, c, d]).
X = [a, b]
?- append(X, [d, c], [a, b, c, d]).
no
11
Terms as Data
 The Dot operator or functor ‘.’ corresponds to
make list with H and T.
 [H | T ] is syntactic sugar for the term .(H,T)
 Lists are terms. The term for the list [a, b, c] is
.(H,T)
.(a, .(b, .(c, [])))
12
Terms as Data
 following terms can be drawn a tree
 There is a one-to-one correspondence
between trees and terms
.(a, .(b, .(c, [])))
∙
∙
∙
a
b
c []
13
Terms : Binary Tree
 Binary trees can be written as terms
 An atom leaf for a leaf
 A functor nonleaf with 2 arguments
leaf
nonleaf(leaf,leaf)
nonleaf(nonleaf(leaf,leaf), nonleaf(leaf,leaf))
nonleaf(nonleaf(leaf,leaf),leaf)
nonleaf(leaf,nonleaf(leaf,leaf))
14
List : tree
 Example 3 A binary search tree is either
empty, or it consists of a node with two binary
search trees as subtrees.
 Each node holds an integer.
 Smaller elements appear in the left subtree of
a node and larger elements appear in the right
subtree.
 Let a term node(K,S,T) represent a tree
K
S T
15
Binary search trees
15
2 16
10
129
0
3
19
10
2 12
9
153
0 16
3
16
Binary search trees
 The rules define a relation member to test
whether an integer appear at some node in a
tree. The two arguments of member are an
integer and a tree.
member(K,_,_).
member(K, node(N,S,_)) :- K < N, member(K, S).
member(K, node(N,_,T)) :- K > N, member(K, T).
17
PROGRAMMING TECHNIQUES
 The strengths of Prolog namely, backtracking
and unification.
 Backtracking allows a solution to be found if
one exists
 Unification allows variables to be used as
placeholders for data to be filled in later.
 Careful use of the techniques in this section
can lead to efficient programs. The programs
rely on left-to-right evaluation of subgoals.
18
Guess and Verify
 A guess-and-verify query has the form
Where guess(S) and verify(S) are subgoals.
 Prolog respond to a query by generating
solutions to guess(S) until a solution satisfying
verify(S) is found. Such queries are also called
generate-and-test queries.
Is there an S such that
guess(S) and verify(S)?
19
Guess and Verify
 Similarly, a guess-and-verify rule has the
following form:
 Example
Conslusion(…) if guess(…,S,…) and verify(…,S,…)
overlap(X, Y) :- member(M, X), member(M, Y).
Two lists X and Y overlap if there is some M that is a
member of both X and Y. The first goal member(M, X)
guesses an M from list X, and the second goal member(M,
Y) verifies that M also appears in list Y.
20
 The rules for member are
member(M, [M |_]).
Member(M, [_ |T]) :- member(M, T).
The first rule says that M is a member of a list with head
M. The second rule says that M is a member of a list if M
is a member of its tail T.
21
Consider query
 These query
 The first goal in this query generates
solutions and the second goal tests to see
whether they are acceptable.
?- overlap([a,b,c,d],[1,2,c,d]).
yes
?- member(M,[a,b,c,d]),member(M,[1,2,c,d]).
22
Consider query
 The solutions generated by the first goal are
 Test the second goal
?- member(M,[a,b,c,d]).
M = a;
M = b;
M = c;
M = d;
no
?- member(a,[1,2,c,d]).
no
?- member(b,[1,2,c,d]).
no
?- member(c,[1,2,c,d]).
yes
23
Hint
 Since computation in Prolog proceeds from
left to right, the order of the subgoals in a
guess-and-verify query can affect efficiency.
 Choose the subgoal with fewer solutions as
the guess goal.
 Example of the effect of goal order
?- X = [1,2,3], member(a,X).
no
?- member(a,X), X = [1,2,3]).
[infinite computation]
24
Variables as Placeholders in Terms
 Variables have been used in rules and
queries but not in terms representing objects.
 Terms containing varibales can be used to
simulate modifiable data structures;
 The variables serve as placeholders for
subterms to be filled in later.
25
Represent Binary Trees in Terms
 The terms leaf and nonleaf(leaf,leaf)
are completely specified.
leaf
nonleaf(leaf,leaf)
26
Partially specified list
 The example list [a, b | X] has
 Its first element : a
 Its second element : b
 Do not yet know what X represents
 “Open list” if its ending in a variable, referred
“end marker variable”
 “Close list” if it is not open.
27
How prolog know variable
 Prolog used machine-generated variables,
written with a leading underscore (“_”)
followed by an integer.
?- L = [a, b | X].
L = [a, |_G172]
X = _G172
Yes
28
 Prolog generates fresh variables each time it
responds to a query or applies a rule.
 An open list can be modified by unifying its
end marker
?- L = [a, b | X], X = [c,Y].
L = [a,b,c |_G236]
X = [c,_G236]
Y = _G236
Yes
29
 Extending an open list by unifying its end
marker.
a b
L X
_172
a b
L X
_236
c
(a) Before X is bound. (b) After X = [c | Y].
30
 Unification of an end-marker variable is akin
to an assignment to that variable.
 List L changes from
[a, b | _172]  [a, b, c | _236]
when _172 unifies with [c | _236]
 Advantage of working with open lists is that
the end of a list can be accessed quickly.
31
Open list implement queues
when a queue is created, where L is an open list with
end marker E
When element a enters queue Q, we get queue R.
When element a leaves queue Q, we get queue R.
q(L,E)
enter(a,Q,R)
leave(a,Q,R)
32
Open list implement queue
?- setup(Q).
?- setup(Q), enter(a,Q,R).
?- setup(Q), enter(a,Q,R), leave(S,R,T).
?- setup(Q), enter(a,Q,R), enter(b,R,S),
leave(X,S,T),leave(Y,T,U), wrapup(q([],[])).
setup(q(X,X)).
enter(A, q(X,Y), q(X,Z)) :- Y = [A | Z].
leave(A, q(X,Z), q(Y,Z)) :- Y = [A | Y].
wrapup(q([],[])).
33
Test queue
?-setup(Q),enter(a,Q,R),enter(b,R,S),leave(X,S,T),
leave(Y,T,U),wrapup(U).
Q = q([a, b], [a, b])
R = q([a, b], [b])
S = q([a, b], [])
X = a
T = q([b], [])
Y = b
U = q([], [])
Yes
?-
34
Operations on a queue
Q
_1
R
_2
a
a
T
_3
b
Q
Q R
setup(Q)
enter(a,Q,R)
enter(b,R,S)
35
Operations on a queue
a
T
_3
b
X
leave(X,S,T)
a
T
_3
b
Y
leave(Y,T,U)
36
Internal Prolog
 A queue q(L,E) consists of open list L with
end marker E.
 The arrows from Q therefore go to the empty
open list _1 with end marker _1.
setup(q(X,X)).
?-setup(Q).
Q = q(_1,_1)
yes
37
Second goal
 To enter A into a queue q(X,Y),
bind Y to a list [A|Z],
where Z is a fresh end marker,
and return q(X,Z).
enter(A,q(X,Y),q(X,Z)):- Y = [A|Z].
?-setup(Q),enter(a,Q,R).
Q = q([a|_2], [a|_2])
R = q([a|_2], _2)
Unifies _1 with [a|_2],where _2 is a fresh end marker
38
 When an element leaves a queue q(L,E), the
resulting queue has the tail of L in place of L.
Note in the diagram to the right of
leave(X,S,T) that the open list for queue T is
the tail of the open list for S.
 The final goal wrapup(U) checks that the
enter and leave operations leave U in an
initial state q(L,E), where L is an empty
openlist with end marker E.
39
Difference Lists
 Difference List are a technique for coping with
such changes.
 Difference List consists of a list and its suffix.
 We write this difference list as
dl(L,E).
40
Contents of Difference List
 The contents of the difference list consist of
the elements that are in L but not in E.
 Examples of difference lists with contents
[a,b] are
dl([a,b],[]).
Dl([a,b,c],[c]).
Dl([a,b|E],E).
Dl([a,b,c|F],[c|F]).
41
CONTROL IN PROLOG
 In the informal equation
 “Logic” refers to the rules and queries in a
logic program and
 “control” refers to how a language computes
a response to a query.
algorithm = logic + control
42
CONTROL IN PROLOG
 Control in Prolog is characterized by two
decisions
 Goal order : Choose the leftmost subgoal.
 Rule order : Select the first applicable rule.
 The response to a query is affected both by
goal order within the query and by rule order
with in the database of facts and rules.
43
CONTROL IN PROLOG
start with a query as the current goal;
while the current goal is nonempty do
choose the leftmost subgoal;
if a rule applies to the subgoal then
select the first applicable rule;
form a new current goal
else
backtrack
end if
end while;
succeed
44
Example
 A sublist S of Z can be specified in the
following seemingly equivalent ways:
 preffix X of Z and suffix S of X.
 suffix S of X and prefix X of Z.
appen1([],Y,Y).
appen1([H|X],Y,[H|Z]):- appen1(X,Y,Z).
Prefix(X,Z) :- appen1(X,Y,Z).
Suffix(Y,Z) :- appen1(X,Y,Z).
appen2([H|X],Y,[H|Z]):- appen2(X,Y,Z).
appen2([],Y,Y).
45
Queries
 The corresponding queries usually produce
the same responses.
 Rule order can also make a difference.
?-prefix(X,[a,b,c]),suffix([e],X).
no
?-suffix([e],X),prefix(X,[a,b,c]).
[infinite computation]
46
Queries
?- appen1(X,[c],Z).
X = []
Z = [c] ;
X = [_G230]
Z = [_G230, c] ;
X = [_G230, _G236]
Z = [_G230, _G236, c] ;
?- appen2(X,[c],Z).
 New Solutions are produced on demand for
47
Unification an Substitutions
 Unification is central to control in Prolog
 Substitution is a function from variables to
terms
48
Applying a Rule to a Goal
 A rule applies to a
subgoal G if its head A unifies with G
 Variables in the rule are renamed before
unification to keep them distinct from
variables in the subgoal.
A :- B1, B2, …, Bn
49
A computation that succeeds without backtracking
GOAL
Suffix([a],L),prefix(L,[a,b,c]).
suffix([a],L) if append(_1,[a],L).
Append(_1,[a],L),prefix(L,[a,b,c]).
{_1[],L[a]} append([],[a],[a]).
Prefix([a],[a,b,c]).
prefix([a],[a,b,c]) if append([a],_2,[a,b,c])
append([a],_2,[a,b,c]).
prefix([a],[a,b,c]) if append([],_2,[b,c])
Append([],_2,[b,c]).
{_2[b,c]} append([],[b,c],[b,c])
yes
50
Prolog Search Trees
51
Goal Order Changes Solutions
52
Cuts
 A cut prunes or “cuts out” and unexplored
part of a Prolog search tree.
 Cuts can therefore be used to make a
computation more efficient by eliminating
futile searching and backtracking.
 Cuts can also be used to implement a form of
negation
53
Cuts
 A cut, written as !, appears as a condition
within a rule. When rule
is applied, the cut tells control to backtrack
past Cj-1,…,C1,B, without considering any
remaining rules for them.
B :- C1,…, Cj-1, !,Cj+1,…,Ck
54
A cut as the First Condition
 Consider rules of the form
 If the goal C fails, then control backtracks
past B without considering any remaining
rules for B. Thus the cut has the effect of
making B fail if C fails.
B :- !, C.
55
Example
b :- c.
b :- d.
b :- e.
b,G
c,G e,G
X
d,G!,d,G
d,G
b :- c.
b :- !,d.
b :- e.
56
Example
 ?-a(X).
a(1) :- b;
a(2) :- e;
b :- c.
b :- d.
a(1) :- b;
a(2) :- e;
b :- !,c.
b :- d.
a(X)
b e
c d Yes
X=2Yes
X=1
backtrack
a(X)
b e
!c d Yes
X=2
backtrack
c
57
The Effect of Cut
 As mentioned earlier, when a rule
is applied during a computation
 The cut tells control to backtrack past Cj-
1,..C1,B without considering any remaining
rules for them.
 The effect of inserting a cut in the middle of a
guess-and-verify rule.
B :- C1,…, Cj-1, !,Cj+1,…,Ck
58
The Effect of Cut
 The right side of a guess-and-verify rule has
the form guess(S), verify(S), where guess(S)
generates potential solutions until one
satisfying verify(S) is found.
 The effect of insering a cut between them, as
is to eliminate all but the first guess.
Conclusion(S) :- guess(S), !, verify(S)
59
a(X) :- b(X).
a(X) :- f(X).
b(X) :- g(X),v(X).
b(X) :- X = 4, v(X).
g(1).
g(2).
g(3).
v(X).
f(5)
a(X) :- b(X).
a(X) :- f(X).
b(X) :- g(X),!,v(X).
b(X) :- X = 4, v(X).
g(1).
g(2).
g(3).
v(X).
f(5)
(a) (b)
60
a(Z)
b(Z) f(5)
g(Z),v(Z) v(4)
v(1) v(2) v(3)
a(Z)
b(Z) f(5)
g(Z),!,v(Z) v(4)
!v(X)
v(1)
v(2) v(3)
(a) (b)
61
Negation as Failure
 The not operator in Prolog is implemented by
the rules
not(X) :- X, !, fail.
not(_).

More Related Content

What's hot

What's hot (20)

Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking 
 
Topological Sort
Topological SortTopological Sort
Topological Sort
 
Disjoint sets
Disjoint setsDisjoint sets
Disjoint sets
 
Introduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in LogicIntroduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in Logic
 
Algorithm Complexity and Main Concepts
Algorithm Complexity and Main ConceptsAlgorithm Complexity and Main Concepts
Algorithm Complexity and Main Concepts
 
SINGLE-SOURCE SHORTEST PATHS
SINGLE-SOURCE SHORTEST PATHS SINGLE-SOURCE SHORTEST PATHS
SINGLE-SOURCE SHORTEST PATHS
 
Exhaustive Search
Exhaustive SearchExhaustive Search
Exhaustive Search
 
Polygon filling
Polygon fillingPolygon filling
Polygon filling
 
PROLOG: Introduction To Prolog
PROLOG: Introduction To PrologPROLOG: Introduction To Prolog
PROLOG: Introduction To Prolog
 
PROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In PrologPROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In Prolog
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Formal Languages and Automata Theory Unit 1
Formal Languages and Automata Theory Unit 1Formal Languages and Automata Theory Unit 1
Formal Languages and Automata Theory Unit 1
 
Ai lecture 06(unit-02)
Ai lecture 06(unit-02)Ai lecture 06(unit-02)
Ai lecture 06(unit-02)
 
Planning
Planning Planning
Planning
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Floyd warshall-algorithm
Floyd warshall-algorithmFloyd warshall-algorithm
Floyd warshall-algorithm
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithm
 
P, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardP, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-Hard
 
Splay Tree
Splay TreeSplay Tree
Splay Tree
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 

Viewers also liked

Prolog Code [Family Tree] by Shahzeb Pirzada
Prolog Code [Family Tree] by Shahzeb PirzadaProlog Code [Family Tree] by Shahzeb Pirzada
Prolog Code [Family Tree] by Shahzeb PirzadaShahzeb Pirzada
 
Introduccion a prolog
Introduccion a prologIntroduccion a prolog
Introduccion a prologJeffoG92
 
Logic programming (1)
Logic programming (1)Logic programming (1)
Logic programming (1)Nitesh Singh
 
PROLOG: Fact Roles And Queries In Prolog
PROLOG: Fact Roles And Queries In PrologPROLOG: Fact Roles And Queries In Prolog
PROLOG: Fact Roles And Queries In PrologPROLOG CONTENT
 
PROLOG: Database Manipulation In Prolog
PROLOG: Database Manipulation In PrologPROLOG: Database Manipulation In Prolog
PROLOG: Database Manipulation In PrologDataminingTools Inc
 
"That scripting language called Prolog"
"That scripting language called Prolog""That scripting language called Prolog"
"That scripting language called Prolog"Sergei Winitzki
 
Knight’s tour algorithm
Knight’s tour algorithmKnight’s tour algorithm
Knight’s tour algorithmHassan Tariq
 
Prolog: Arithmetic Operations In Prolog
Prolog: Arithmetic Operations In PrologProlog: Arithmetic Operations In Prolog
Prolog: Arithmetic Operations In PrologPROLOG CONTENT
 
Logic Programming and Prolog
Logic Programming and PrologLogic Programming and Prolog
Logic Programming and PrologSadegh Dorri N.
 
اجابات البرولوج
اجابات البرولوجاجابات البرولوج
اجابات البرولوجAmmar Khalid
 
Artificial intelligence Prolog Language
Artificial intelligence Prolog LanguageArtificial intelligence Prolog Language
Artificial intelligence Prolog LanguageREHMAT ULLAH
 
PROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In PrologPROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In PrologDataminingTools Inc
 

Viewers also liked (18)

Prolog Code [Family Tree] by Shahzeb Pirzada
Prolog Code [Family Tree] by Shahzeb PirzadaProlog Code [Family Tree] by Shahzeb Pirzada
Prolog Code [Family Tree] by Shahzeb Pirzada
 
Prolog basics
Prolog basicsProlog basics
Prolog basics
 
Introduccion a prolog
Introduccion a prologIntroduccion a prolog
Introduccion a prolog
 
Chaps 1-3-ai-prolog
Chaps 1-3-ai-prologChaps 1-3-ai-prolog
Chaps 1-3-ai-prolog
 
Logic programming (1)
Logic programming (1)Logic programming (1)
Logic programming (1)
 
PROLOG: Fact Roles And Queries In Prolog
PROLOG: Fact Roles And Queries In PrologPROLOG: Fact Roles And Queries In Prolog
PROLOG: Fact Roles And Queries In Prolog
 
Prolog 7-Languages
Prolog 7-LanguagesProlog 7-Languages
Prolog 7-Languages
 
PROLOG: Database Manipulation In Prolog
PROLOG: Database Manipulation In PrologPROLOG: Database Manipulation In Prolog
PROLOG: Database Manipulation In Prolog
 
Ch10 Recursion
Ch10 RecursionCh10 Recursion
Ch10 Recursion
 
"That scripting language called Prolog"
"That scripting language called Prolog""That scripting language called Prolog"
"That scripting language called Prolog"
 
Knight’s tour algorithm
Knight’s tour algorithmKnight’s tour algorithm
Knight’s tour algorithm
 
Knight's Tour
Knight's TourKnight's Tour
Knight's Tour
 
Prolog: Arithmetic Operations In Prolog
Prolog: Arithmetic Operations In PrologProlog: Arithmetic Operations In Prolog
Prolog: Arithmetic Operations In Prolog
 
Logic Programming and Prolog
Logic Programming and PrologLogic Programming and Prolog
Logic Programming and Prolog
 
Logic programming in python
Logic programming in pythonLogic programming in python
Logic programming in python
 
اجابات البرولوج
اجابات البرولوجاجابات البرولوج
اجابات البرولوج
 
Artificial intelligence Prolog Language
Artificial intelligence Prolog LanguageArtificial intelligence Prolog Language
Artificial intelligence Prolog Language
 
PROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In PrologPROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In Prolog
 

Similar to Prolog programming

PrologListsGraphs.ppt
PrologListsGraphs.pptPrologListsGraphs.ppt
PrologListsGraphs.pptPRITISHDASH8
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdfAshaWankar1
 
Functions And Relations
Functions And RelationsFunctions And Relations
Functions And Relationsandrewhickson
 
Bai tap-prolog-da-tap-hop-9889
Bai tap-prolog-da-tap-hop-9889Bai tap-prolog-da-tap-hop-9889
Bai tap-prolog-da-tap-hop-9889anhsaobang1289
 
Functions And Relations
Functions And RelationsFunctions And Relations
Functions And Relationsandrewhickson
 
Addressing Formulas for Sparse Matrices Using Column Major in 1D Arrays.pptx
Addressing Formulas for Sparse Matrices Using Column Major in 1D Arrays.pptxAddressing Formulas for Sparse Matrices Using Column Major in 1D Arrays.pptx
Addressing Formulas for Sparse Matrices Using Column Major in 1D Arrays.pptxAshishPandey502
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in pythonSangita Panchal
 
Relation function
Relation functionRelation function
Relation functionBiswa Nayak
 
Relation function
Relation functionRelation function
Relation functionmentorsnet
 
Set Concepts
Set ConceptsSet Concepts
Set Conceptsshbest
 
Discrete Math Chapter 2: Basic Structures: Sets, Functions, Sequences, Sums, ...
Discrete Math Chapter 2: Basic Structures: Sets, Functions, Sequences, Sums, ...Discrete Math Chapter 2: Basic Structures: Sets, Functions, Sequences, Sums, ...
Discrete Math Chapter 2: Basic Structures: Sets, Functions, Sequences, Sums, ...Amr Rashed
 
15CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 315CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 3Syed Mustafa
 

Similar to Prolog programming (20)

PrologListsGraphs.ppt
PrologListsGraphs.pptPrologListsGraphs.ppt
PrologListsGraphs.ppt
 
Section3 Prologppt
Section3 PrologpptSection3 Prologppt
Section3 Prologppt
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Functions And Relations
Functions And RelationsFunctions And Relations
Functions And Relations
 
Python lecture 07
Python lecture 07Python lecture 07
Python lecture 07
 
Bai tap-prolog-da-tap-hop-9889
Bai tap-prolog-da-tap-hop-9889Bai tap-prolog-da-tap-hop-9889
Bai tap-prolog-da-tap-hop-9889
 
Functions And Relations
Functions And RelationsFunctions And Relations
Functions And Relations
 
Addressing Formulas for Sparse Matrices Using Column Major in 1D Arrays.pptx
Addressing Formulas for Sparse Matrices Using Column Major in 1D Arrays.pptxAddressing Formulas for Sparse Matrices Using Column Major in 1D Arrays.pptx
Addressing Formulas for Sparse Matrices Using Column Major in 1D Arrays.pptx
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in python
 
Pytho lists
Pytho listsPytho lists
Pytho lists
 
Relation function
Relation functionRelation function
Relation function
 
Relation function
Relation functionRelation function
Relation function
 
Lecture-5.pdf
Lecture-5.pdfLecture-5.pdf
Lecture-5.pdf
 
Set Concepts
Set ConceptsSet Concepts
Set Concepts
 
Array
ArrayArray
Array
 
Discrete Math Chapter 2: Basic Structures: Sets, Functions, Sequences, Sums, ...
Discrete Math Chapter 2: Basic Structures: Sets, Functions, Sequences, Sums, ...Discrete Math Chapter 2: Basic Structures: Sets, Functions, Sequences, Sums, ...
Discrete Math Chapter 2: Basic Structures: Sets, Functions, Sequences, Sums, ...
 
Python lists
Python listsPython lists
Python lists
 
presentasi
presentasipresentasi
presentasi
 
15CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 315CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 3
 

More from Harry Potter

How to build a rest api.pptx
How to build a rest api.pptxHow to build a rest api.pptx
How to build a rest api.pptxHarry Potter
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningHarry Potter
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningHarry Potter
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryHarry Potter
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceHarry Potter
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksHarry Potter
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsHarry Potter
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheHarry Potter
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsHarry Potter
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesHarry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHarry Potter
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous classHarry Potter
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisHarry Potter
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteHarry Potter
 

More from Harry Potter (20)

How to build a rest api.pptx
How to build a rest api.pptxHow to build a rest api.pptx
How to build a rest api.pptx
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of 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
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
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
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Smm & caching
Smm & cachingSmm & caching
Smm & caching
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Object model
Object modelObject model
Object model
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Api crash
Api crashApi crash
Api crash
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 

Recently uploaded

Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
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
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
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
 
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
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 

Recently uploaded (20)

Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
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...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
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
 
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
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 

Prolog programming

  • 2. 2 Prolog ProgrammingProlog Programming  DATA STRUCTURES IN PROLOG  PROGRAMMING TECHNIQUES  CONTROL IN PROLOG  CUTS
  • 3. 3 DATA STRUCTURES IN PROLOG  Lists in Prolog List notation is a way of writing terms  Terms as Data Term correspond with list
  • 4. 4 Lists in Prolog  The simplest way of writing a list is to enumerate its elements. The list consisting of the 3 atoms a, b and c can be written as [a, b, c] The list that doesn’t have elements called empty list denoted as [ ]
  • 5. 5 Lists in Prolog  We can also specify an initial sequence of elements and a trailing list, separated by | The list [a, b, c] can also be written as [a, b, c | [ ] ] [a, b | [c] ] [a | [b, c] ]
  • 6. 6 Lists : Head & Tail  A special case of this notation is a list with head H and tail T, written as [H|T]  The head is the first element of a list, and  The tail is the list consisting of the remaining elements. The list [a, b, c] can also be separated as • Head:The first element is a • Tail:The list of remaining elements = [b, c]
  • 7. 7 Lists : Unification  Unification can be used to extract the components of a list, so explicit operators for extracting the head and tail are not needed. The solution of the query  Bind variable H to the head and variable T to the tail of list [a, b, c]. ?- [H | T] = [a, b, c]. H = a T = [b, c]
  • 8. 8 Lists : Specified terms  The query (partially specified terms)  The term [ a | T ] is a partial specification of a list with head a and unknown tail denoted by variable T.  Similarly, [ H, b, c] is a partial specification of a list with unknown head H and tail [b, c].  These two specification to unify H = a, T =[b,c] ?- [a | T] = [H, b, c]. T = [b, c] H = a
  • 9. 9 Lists in Prolog  Example 2 The append relation on lists is defined by the following rules: Append([ ], Y, Y). Append([H | X], Y, [H | Z]) :- append(X,Y,Z). In words, The result of appending the empty list [ ] and a list Y is Y. If the result of appending X and Y is Z, then the result of appending [H | X] and Y is [H | Z]
  • 10. 10 Lists : Compute Arguments  The rules for append can be used to compute any one of the arguments from the other two:  Inconsistent arguments are rejected ?- append([a, b], [c, d], Z). Z = [a, b, c, d] ?- append([a, b], Y, [a, b, c, d]). Y = [c, d] ?- append(X, [c, d], [a, b, c, d]). X = [a, b] ?- append(X, [d, c], [a, b, c, d]). no
  • 11. 11 Terms as Data  The Dot operator or functor ‘.’ corresponds to make list with H and T.  [H | T ] is syntactic sugar for the term .(H,T)  Lists are terms. The term for the list [a, b, c] is .(H,T) .(a, .(b, .(c, [])))
  • 12. 12 Terms as Data  following terms can be drawn a tree  There is a one-to-one correspondence between trees and terms .(a, .(b, .(c, []))) ∙ ∙ ∙ a b c []
  • 13. 13 Terms : Binary Tree  Binary trees can be written as terms  An atom leaf for a leaf  A functor nonleaf with 2 arguments leaf nonleaf(leaf,leaf) nonleaf(nonleaf(leaf,leaf), nonleaf(leaf,leaf)) nonleaf(nonleaf(leaf,leaf),leaf) nonleaf(leaf,nonleaf(leaf,leaf))
  • 14. 14 List : tree  Example 3 A binary search tree is either empty, or it consists of a node with two binary search trees as subtrees.  Each node holds an integer.  Smaller elements appear in the left subtree of a node and larger elements appear in the right subtree.  Let a term node(K,S,T) represent a tree K S T
  • 15. 15 Binary search trees 15 2 16 10 129 0 3 19 10 2 12 9 153 0 16 3
  • 16. 16 Binary search trees  The rules define a relation member to test whether an integer appear at some node in a tree. The two arguments of member are an integer and a tree. member(K,_,_). member(K, node(N,S,_)) :- K < N, member(K, S). member(K, node(N,_,T)) :- K > N, member(K, T).
  • 17. 17 PROGRAMMING TECHNIQUES  The strengths of Prolog namely, backtracking and unification.  Backtracking allows a solution to be found if one exists  Unification allows variables to be used as placeholders for data to be filled in later.  Careful use of the techniques in this section can lead to efficient programs. The programs rely on left-to-right evaluation of subgoals.
  • 18. 18 Guess and Verify  A guess-and-verify query has the form Where guess(S) and verify(S) are subgoals.  Prolog respond to a query by generating solutions to guess(S) until a solution satisfying verify(S) is found. Such queries are also called generate-and-test queries. Is there an S such that guess(S) and verify(S)?
  • 19. 19 Guess and Verify  Similarly, a guess-and-verify rule has the following form:  Example Conslusion(…) if guess(…,S,…) and verify(…,S,…) overlap(X, Y) :- member(M, X), member(M, Y). Two lists X and Y overlap if there is some M that is a member of both X and Y. The first goal member(M, X) guesses an M from list X, and the second goal member(M, Y) verifies that M also appears in list Y.
  • 20. 20  The rules for member are member(M, [M |_]). Member(M, [_ |T]) :- member(M, T). The first rule says that M is a member of a list with head M. The second rule says that M is a member of a list if M is a member of its tail T.
  • 21. 21 Consider query  These query  The first goal in this query generates solutions and the second goal tests to see whether they are acceptable. ?- overlap([a,b,c,d],[1,2,c,d]). yes ?- member(M,[a,b,c,d]),member(M,[1,2,c,d]).
  • 22. 22 Consider query  The solutions generated by the first goal are  Test the second goal ?- member(M,[a,b,c,d]). M = a; M = b; M = c; M = d; no ?- member(a,[1,2,c,d]). no ?- member(b,[1,2,c,d]). no ?- member(c,[1,2,c,d]). yes
  • 23. 23 Hint  Since computation in Prolog proceeds from left to right, the order of the subgoals in a guess-and-verify query can affect efficiency.  Choose the subgoal with fewer solutions as the guess goal.  Example of the effect of goal order ?- X = [1,2,3], member(a,X). no ?- member(a,X), X = [1,2,3]). [infinite computation]
  • 24. 24 Variables as Placeholders in Terms  Variables have been used in rules and queries but not in terms representing objects.  Terms containing varibales can be used to simulate modifiable data structures;  The variables serve as placeholders for subterms to be filled in later.
  • 25. 25 Represent Binary Trees in Terms  The terms leaf and nonleaf(leaf,leaf) are completely specified. leaf nonleaf(leaf,leaf)
  • 26. 26 Partially specified list  The example list [a, b | X] has  Its first element : a  Its second element : b  Do not yet know what X represents  “Open list” if its ending in a variable, referred “end marker variable”  “Close list” if it is not open.
  • 27. 27 How prolog know variable  Prolog used machine-generated variables, written with a leading underscore (“_”) followed by an integer. ?- L = [a, b | X]. L = [a, |_G172] X = _G172 Yes
  • 28. 28  Prolog generates fresh variables each time it responds to a query or applies a rule.  An open list can be modified by unifying its end marker ?- L = [a, b | X], X = [c,Y]. L = [a,b,c |_G236] X = [c,_G236] Y = _G236 Yes
  • 29. 29  Extending an open list by unifying its end marker. a b L X _172 a b L X _236 c (a) Before X is bound. (b) After X = [c | Y].
  • 30. 30  Unification of an end-marker variable is akin to an assignment to that variable.  List L changes from [a, b | _172]  [a, b, c | _236] when _172 unifies with [c | _236]  Advantage of working with open lists is that the end of a list can be accessed quickly.
  • 31. 31 Open list implement queues when a queue is created, where L is an open list with end marker E When element a enters queue Q, we get queue R. When element a leaves queue Q, we get queue R. q(L,E) enter(a,Q,R) leave(a,Q,R)
  • 32. 32 Open list implement queue ?- setup(Q). ?- setup(Q), enter(a,Q,R). ?- setup(Q), enter(a,Q,R), leave(S,R,T). ?- setup(Q), enter(a,Q,R), enter(b,R,S), leave(X,S,T),leave(Y,T,U), wrapup(q([],[])). setup(q(X,X)). enter(A, q(X,Y), q(X,Z)) :- Y = [A | Z]. leave(A, q(X,Z), q(Y,Z)) :- Y = [A | Y]. wrapup(q([],[])).
  • 33. 33 Test queue ?-setup(Q),enter(a,Q,R),enter(b,R,S),leave(X,S,T), leave(Y,T,U),wrapup(U). Q = q([a, b], [a, b]) R = q([a, b], [b]) S = q([a, b], []) X = a T = q([b], []) Y = b U = q([], []) Yes ?-
  • 34. 34 Operations on a queue Q _1 R _2 a a T _3 b Q Q R setup(Q) enter(a,Q,R) enter(b,R,S)
  • 35. 35 Operations on a queue a T _3 b X leave(X,S,T) a T _3 b Y leave(Y,T,U)
  • 36. 36 Internal Prolog  A queue q(L,E) consists of open list L with end marker E.  The arrows from Q therefore go to the empty open list _1 with end marker _1. setup(q(X,X)). ?-setup(Q). Q = q(_1,_1) yes
  • 37. 37 Second goal  To enter A into a queue q(X,Y), bind Y to a list [A|Z], where Z is a fresh end marker, and return q(X,Z). enter(A,q(X,Y),q(X,Z)):- Y = [A|Z]. ?-setup(Q),enter(a,Q,R). Q = q([a|_2], [a|_2]) R = q([a|_2], _2) Unifies _1 with [a|_2],where _2 is a fresh end marker
  • 38. 38  When an element leaves a queue q(L,E), the resulting queue has the tail of L in place of L. Note in the diagram to the right of leave(X,S,T) that the open list for queue T is the tail of the open list for S.  The final goal wrapup(U) checks that the enter and leave operations leave U in an initial state q(L,E), where L is an empty openlist with end marker E.
  • 39. 39 Difference Lists  Difference List are a technique for coping with such changes.  Difference List consists of a list and its suffix.  We write this difference list as dl(L,E).
  • 40. 40 Contents of Difference List  The contents of the difference list consist of the elements that are in L but not in E.  Examples of difference lists with contents [a,b] are dl([a,b],[]). Dl([a,b,c],[c]). Dl([a,b|E],E). Dl([a,b,c|F],[c|F]).
  • 41. 41 CONTROL IN PROLOG  In the informal equation  “Logic” refers to the rules and queries in a logic program and  “control” refers to how a language computes a response to a query. algorithm = logic + control
  • 42. 42 CONTROL IN PROLOG  Control in Prolog is characterized by two decisions  Goal order : Choose the leftmost subgoal.  Rule order : Select the first applicable rule.  The response to a query is affected both by goal order within the query and by rule order with in the database of facts and rules.
  • 43. 43 CONTROL IN PROLOG start with a query as the current goal; while the current goal is nonempty do choose the leftmost subgoal; if a rule applies to the subgoal then select the first applicable rule; form a new current goal else backtrack end if end while; succeed
  • 44. 44 Example  A sublist S of Z can be specified in the following seemingly equivalent ways:  preffix X of Z and suffix S of X.  suffix S of X and prefix X of Z. appen1([],Y,Y). appen1([H|X],Y,[H|Z]):- appen1(X,Y,Z). Prefix(X,Z) :- appen1(X,Y,Z). Suffix(Y,Z) :- appen1(X,Y,Z). appen2([H|X],Y,[H|Z]):- appen2(X,Y,Z). appen2([],Y,Y).
  • 45. 45 Queries  The corresponding queries usually produce the same responses.  Rule order can also make a difference. ?-prefix(X,[a,b,c]),suffix([e],X). no ?-suffix([e],X),prefix(X,[a,b,c]). [infinite computation]
  • 46. 46 Queries ?- appen1(X,[c],Z). X = [] Z = [c] ; X = [_G230] Z = [_G230, c] ; X = [_G230, _G236] Z = [_G230, _G236, c] ; ?- appen2(X,[c],Z).  New Solutions are produced on demand for
  • 47. 47 Unification an Substitutions  Unification is central to control in Prolog  Substitution is a function from variables to terms
  • 48. 48 Applying a Rule to a Goal  A rule applies to a subgoal G if its head A unifies with G  Variables in the rule are renamed before unification to keep them distinct from variables in the subgoal. A :- B1, B2, …, Bn
  • 49. 49 A computation that succeeds without backtracking GOAL Suffix([a],L),prefix(L,[a,b,c]). suffix([a],L) if append(_1,[a],L). Append(_1,[a],L),prefix(L,[a,b,c]). {_1[],L[a]} append([],[a],[a]). Prefix([a],[a,b,c]). prefix([a],[a,b,c]) if append([a],_2,[a,b,c]) append([a],_2,[a,b,c]). prefix([a],[a,b,c]) if append([],_2,[b,c]) Append([],_2,[b,c]). {_2[b,c]} append([],[b,c],[b,c]) yes
  • 52. 52 Cuts  A cut prunes or “cuts out” and unexplored part of a Prolog search tree.  Cuts can therefore be used to make a computation more efficient by eliminating futile searching and backtracking.  Cuts can also be used to implement a form of negation
  • 53. 53 Cuts  A cut, written as !, appears as a condition within a rule. When rule is applied, the cut tells control to backtrack past Cj-1,…,C1,B, without considering any remaining rules for them. B :- C1,…, Cj-1, !,Cj+1,…,Ck
  • 54. 54 A cut as the First Condition  Consider rules of the form  If the goal C fails, then control backtracks past B without considering any remaining rules for B. Thus the cut has the effect of making B fail if C fails. B :- !, C.
  • 55. 55 Example b :- c. b :- d. b :- e. b,G c,G e,G X d,G!,d,G d,G b :- c. b :- !,d. b :- e.
  • 56. 56 Example  ?-a(X). a(1) :- b; a(2) :- e; b :- c. b :- d. a(1) :- b; a(2) :- e; b :- !,c. b :- d. a(X) b e c d Yes X=2Yes X=1 backtrack a(X) b e !c d Yes X=2 backtrack c
  • 57. 57 The Effect of Cut  As mentioned earlier, when a rule is applied during a computation  The cut tells control to backtrack past Cj- 1,..C1,B without considering any remaining rules for them.  The effect of inserting a cut in the middle of a guess-and-verify rule. B :- C1,…, Cj-1, !,Cj+1,…,Ck
  • 58. 58 The Effect of Cut  The right side of a guess-and-verify rule has the form guess(S), verify(S), where guess(S) generates potential solutions until one satisfying verify(S) is found.  The effect of insering a cut between them, as is to eliminate all but the first guess. Conclusion(S) :- guess(S), !, verify(S)
  • 59. 59 a(X) :- b(X). a(X) :- f(X). b(X) :- g(X),v(X). b(X) :- X = 4, v(X). g(1). g(2). g(3). v(X). f(5) a(X) :- b(X). a(X) :- f(X). b(X) :- g(X),!,v(X). b(X) :- X = 4, v(X). g(1). g(2). g(3). v(X). f(5) (a) (b)
  • 60. 60 a(Z) b(Z) f(5) g(Z),v(Z) v(4) v(1) v(2) v(3) a(Z) b(Z) f(5) g(Z),!,v(Z) v(4) !v(X) v(1) v(2) v(3) (a) (b)
  • 61. 61 Negation as Failure  The not operator in Prolog is implemented by the rules not(X) :- X, !, fail. not(_).