SlideShare a Scribd company logo
1
Logic ProgrammingLogic Programming
And PrologAnd Prolog
MacLennan - Chapter 13MacLennan - Chapter 13
ECE Department of Tehran UniversityECE Department of Tehran University
Programming Language Design CourseProgramming Language Design Course
Student LectureStudent Lecture
Sadegh Dorri Nogoorani (http://ce.sharif.edu/~dorri)Sadegh Dorri Nogoorani (http://ce.sharif.edu/~dorri)
2ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
55thth
-Generation Languages-Generation Languages
Declarative (nonprocedural)Declarative (nonprocedural)
 Functional Programming
 Logic Programming
ImperativeImperative
 Object Oriented Programming
3ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Nonprocedural ProgrammingNonprocedural Programming
Sorting procedurally:Sorting procedurally:
1. Find the min in the remained numbers.
2. Swap it with the first number.
3. Repeat steps 1,2 until no number remains.
Sorting nonprocedurally:Sorting nonprocedurally:
1. B is a sorting of A ↔ B is a permutation of A and B is
ordered.
2. B is ordered ↔ for each i<j: B[i] ≤ B[j]
Which isWhich is higher levelhigher level??
4ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Automated Theorem ProvingAutomated Theorem Proving
A.T.P:A.T.P: Developing programs that can construct formal proofsDeveloping programs that can construct formal proofs
of propositions stated in a symbolic language.of propositions stated in a symbolic language.
ConstructConstruct the desired result to prove its existence (mostthe desired result to prove its existence (most
A.T.P.’s).A.T.P.’s).
InIn Logic ProgrammingLogic Programming,, programs are expressed in the form ofprograms are expressed in the form of
propositions and the theorem prover constructs the result(s).propositions and the theorem prover constructs the result(s).
J. A. Robinson: A program is a theory (in some logic) andJ. A. Robinson: A program is a theory (in some logic) and
computation is deduction from the theory.computation is deduction from the theory.
5ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Programming In Logic (Prolog)Programming In Logic (Prolog)
Developed inDeveloped in Groupe d’Intelligence ArtificielleGroupe d’Intelligence Artificielle (GIA)(GIA)
of the University of Marseilles (early 70s) to processof the University of Marseilles (early 70s) to process
a natural language (French).a natural language (French).
Interpreters: Algol-W (72), FORTRAN (73), PascalInterpreters: Algol-W (72), FORTRAN (73), Pascal
(76), Implemented on many platforms (Now)(76), Implemented on many platforms (Now)
Application in AI since mid-70sApplication in AI since mid-70s
Successor to LISP for AI appsSuccessor to LISP for AI apps
Not standardized (but has ISO standard now)Not standardized (but has ISO standard now)
6
Structural OrganizationStructural Organization
13.213.2
7
parentparent(X,Y) :-(X,Y) :- fatherfather(X,Y).(X,Y).
parentparent(X,Y) :-(X,Y) :- mothermother(X,Y).(X,Y).
grandparentgrandparent(X,Z) :-(X,Z) :- parentparent(X,Y),(X,Y), parentparent(Y,Z).(Y,Z).
ancestorancestor(X,Z) :-(X,Z) :- parentparent(X,Z).(X,Z).
ancestorancestor(X,Y) :-(X,Y) :- parentparent(X,Y),(X,Y), ancestorancestor(Y,Z).(Y,Z).
siblingsibling(X,Y) :-(X,Y) :- mothermother(M,X),(M,X), mothermother(M,Y),(M,Y),
fatherfather(F,X),(F,X), fatherfather(F,Y), X = Y.(F,Y), X = Y.
cousincousin(X,Y) :-(X,Y) :- parentparent(U,X),(U,X), parentparent(V,Y),(V,Y), siblingsibling(U,V).(U,V).
fatherfather(albert, jeffrey).(albert, jeffrey).
mothermother(alice, jeffrey).(alice, jeffrey).
fatherfather(albert, george).(albert, george).
mothermother(alice, george).(alice, george).
fatherfather(john, mary).(john, mary).
mothermother(sue, mary).(sue, mary).
fatherfather(george, cindy).(george, cindy).
mothermother(mary, cindy).(mary, cindy).
fatherfather(george, victor).(george, victor).
mothermother(mary, victor).(mary, victor).
8
?-?- [kinship].[kinship].
% kinship compiled 0.00 sec, 3,016 bytes% kinship compiled 0.00 sec, 3,016 bytes
YesYes
?-?- ancestor(X, cindy), sibling(X, jeffrey).ancestor(X, cindy), sibling(X, jeffrey).
X = georgeX = george ↵↵
YesYes
?-?- grandparent(albert, victor).grandparent(albert, victor).
YesYes
?-?- cousin(alice, john).cousin(alice, john).
NoNo
?-?- sibling(A,B).sibling(A,B).
A = jeffrey, B = georgeA = jeffrey, B = george ;; ↵↵
A = george, B = jeffreyA = george, B = jeffrey ;; ↵↵
A = cindy, B = victorA = cindy, B = victor ;; ↵↵
A = victor, B = cindyA = victor, B = cindy ;; ↵↵
NoNo
SWI Prolog
9ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
ClausesClauses
Programs are constructed from A number ofPrograms are constructed from A number of
clausesclauses: <head>: <head> :-:- <body><body>
Clauses have three forms:Clauses have three forms:
 hypotheses (facts)
 conditions (rules)
 goals
Both <headBoth <head>> and <body> are composed ofand <body> are composed of
relationshipsrelationships (also called(also called predicationspredications oror
literalsliterals))
assertions (database)
questions
10ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
RelationshipsRelationships
Represent properties of and relations among theRepresent properties of and relations among the
individualsindividuals
A relationship is application of aA relationship is application of a predicatepredicate to one orto one or
moremore termsterms
Terms:Terms:
 atoms (or constants): john, 25, …
 variables (begin with uppercase letters): X, …
 compounds
Horn clause formHorn clause form:: At most one relationship inAt most one relationship in
<head><head>
11ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Compound TermsCompound Terms
It isIt is moremore convenient to describe individuals withoutconvenient to describe individuals without
giving them names (giving them names (expressionsexpressions oror compoundscompounds asas
terms).terms).
usingusing functorsfunctors (tags):(tags):
d(X, plus(U,V), plus(DU,DV)) :- d(X,U,DU), d(X,V,DV).
or usingor using infix functorsinfix functors::
d(X, U+V, DU+DV) :- d(X,U,DU), d(X,V,DV).
instead ofinstead of
d(X,W,Z) :- sum(U,V,W), d(X,U,DU), d(X,V,DV),
sum(DU,DV,Z).
with less readability and some other things…with less readability and some other things…
12
Data StructuresData Structures
13.313.3
13ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Primitives and ConstructorsPrimitives and Constructors
FewFew primitives andprimitives and NoNo constructors.constructors.
Data types and data structures are definedData types and data structures are defined
implicitlyimplicitly by theirby their propertiesproperties..
14ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Example (datatype)Example (datatype)
Natural number arithmeticNatural number arithmetic
sum(succ(X), Y, succ(Z)) :- sum(X,Y,Z).
sum(0,X,X).
dif(X,Y,Z) :- sum(Z,Y,X).
:-sum(succ(succ(0)),succ(succ(succ(0))),A).
A = succ(succ(succ(succ(succ(0)))))
Very inefficient! (Why such a decision?)Very inefficient! (Why such a decision?)
Use ofUse of ‘is’‘is’ operator (unidirectional)operator (unidirectional)
15ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
PrinciplesPrinciples
SimplicitySimplicity
 Small number of built-in data types and operations
RegularityRegularity
 Uniform treatment of all data types as predicates
and terms
16ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Data StructuresData Structures
Compound termsCompound terms can represent data structurescan represent data structures
Example:Example: ListsLists in LISPin LISP
(car (cons X L)) = X
(cdr (cons X L)) = L
(cons (car L) (cdr L)) = L, for nonnull L
17ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Lists in PrologLists in Prolog
Using compound terms:Using compound terms:
car( cons(X,L), X).
cdr( cons(X,L), L).
list(nil).
list(cons(X,L)) :- list(L).
null(nil).
What about null(L)?What about null(L)?
How to accomplish (car (consHow to accomplish (car (cons ‘‘(a b)(a b) ‘‘(c d)))?(c d)))?
18ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Some Syntactic SugarSome Syntactic Sugar
UsingUsing ‘.’‘.’ infix functor (in some systems)infix functor (in some systems)
instead of cons:instead of cons:
 Clauses?
Most Prolog systems allow the abbreviation:Most Prolog systems allow the abbreviation:
 [X1, X2, …, Xn] = X1. X2. … .Xn.nil
 [ ] = nil
 ‘.’ is right associative!
19ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Component SelectionComponent Selection
Implicitly done byImplicitly done by pattern matchingpattern matching ((unificationunification).).
append( [ ], L, L).
append( X.P, L, X.Q) :- append(P,L,Q).
Compare with LISP append:Compare with LISP append:
(defun append (M L)
(if (null M)
L
(cons (car M) (append (cdr M) L)) ))
Taking apartTaking apart in terms ofin terms of putting togetherputting together!!
 What X and P are cons’d to create M?
 What number do I add to 3 to get 5 (instead of 5-3)
Efficient!?Efficient!?
20ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Complex StructuresComplex Structures
A tree using lists (in LISP):A tree using lists (in LISP):
 (times (plus x y) (plus y 1))
Using compound terms directly (as records):Using compound terms directly (as records):
 times(plus(x, y), plus(y, 1))
Using predicates directly:Using predicates directly:
 sum(x, y, t1).
 sum(y, 1, t2).
 prod(t1, t2, t3).
Which isWhich is betterbetter??
21ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Why Not Predicates?Why Not Predicates?
Symbolic differentiation using predicateSymbolic differentiation using predicate
structured expressions:structured expressions:
d(X,W,Z) :- sum(U,V,W), d(X,Y,DU), d(X,V,DV),
sum(DU,DV,Z).
d(X,W,Z) :- prod(U,V,W), d(X,U,DU), d(X,V,DV),
prod(DU,V,A), prod(U,DV,B), sum(A,B,Z).
d(X,X,1).
d(X,C,0) :- atomic(C), C = X.
22ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Why Not Predicates? (cont.)Why Not Predicates? (cont.)
Waste use of intermediate (temporary)Waste use of intermediate (temporary)
variablesvariables
Less readabilityLess readability
Unexpected answers!Unexpected answers!
sum(x,1,z).
:- d(x,z,D).
No
 Why? What did you expect?
 How to correct it?
23ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Closed World ModelClosed World Model
AllAll that is true is what can bethat is true is what can be provedproved on the basis of the factson the basis of the facts
and rules in the database.and rules in the database.
Very reasonable inVery reasonable in object-orientedobject-oriented apps (modeling a real orapps (modeling a real or
imagined world)imagined world)
 All existing objects are defined.
 No object have a given property which cannot be found in db.
Not suitable forNot suitable for mathematical problemsmathematical problems (Why?)(Why?)
 An object is generally take to exist if its existance doesn’t contradict
the axioms.
PredicatesPredicates are better for OO-relationships,are better for OO-relationships, CompoundsCompounds forfor
mathematical ones (Why?)mathematical ones (Why?)
 We cannot assume existance of 1+0 whenever needed.
24ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
An Argument!An Argument!
What’s the answer?What’s the answer?
equal(X,X).
:- equal(f(Y),Y).
?
What’s theWhat’s the logicallogical meaning? (meaning? (occurs checkoccurs check))
AnyAny otherother meaning?meaning?
Can it be represented in aCan it be represented in a finite amountfinite amount ofof
memory?memory?
Should weShould we detectdetect it?it?
25
Control StructuresControl Structures
13.413.4
26ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Algorithm = Logic + ControlAlgorithm = Logic + Control
N. Wirth:N. Wirth: Program = data structure + algorithmProgram = data structure + algorithm
R. Kowalski:R. Kowalski: Algorithm = logic + controlAlgorithm = logic + control
In conventional programming:In conventional programming:
 Logic of a program is closely related to its control
 A change in order of statements alters the meaning of program
In (pure) logic programming:In (pure) logic programming:
 Logic (logic phase) is determined by logical interrelationships of the
clauses not their order.
 Control (control phase) affects the order in which actions occur in time
and only affects the efficiency of programs.
Orthogonality PrincipleOrthogonality Principle
27ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Top-Down vs. Bottom-Up ControlTop-Down vs. Bottom-Up Control
Top-down ≈Top-down ≈ RecursionRecursion::
 Try to reach the hypotheses
from the goal.
Bottom-up ≈Bottom-up ≈ IterationIteration::
 Try to reach the goal from the
hypotheses.
Hybrid:Hybrid:
 Work from both the goals and
the hypotheses and try to meet
in the middle.
Which one is better?Which one is better?
:- fib(3, F).:- fib(3, F).
N=3, M=2, K=1,N=3, M=2, K=1,
F=G+HF=G+H
:- fib(2,F).:- fib(2,F).
N=2, M=1, k=0,N=2, M=1, k=0,
F=G+HF=G+H
:- fib(1,F).:- fib(1,F).
F=1F=1
:- fib(1,F).:- fib(1,F).
F=1F=1
:- fib(1,1).:- fib(1,1).
:- fib(0,F).:- fib(0,F).
F=1F=1
:- fib(1,1).:- fib(1,1). :- fib(0,1).:- fib(0,1).
fib(0,1). fib(1,1).
fib(N,F) :- N=M+1, M=K+1, fib(M,G),
fib(K,H), F=G+H, N>1.
28ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Procedural InterpretationProcedural Interpretation
We have seenWe have seen logicallogical andand recordrecord (data structure)(data structure) interpretationsinterpretations..
Clauses can also be viewed asClauses can also be viewed as procedure invocationsprocedure invocations::
 <head>: proc. definition
 <body>: proc. body (a series of proc. calls)
 Multiple definitions: branches of a conditional (case)
 fib() example…
Procedure calls can be executed in any order or evenProcedure calls can be executed in any order or even
concurrently! (pure logic)concurrently! (pure logic)
Input/Output params are not distinguished!Input/Output params are not distinguished!
 fib(3,3) ↔ true. fib(3,F) ↔ F=3. fib(N,3) ↔ N=3. fib(N,F) ↔ ?
29ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Unify, Fail, Redo…Unify, Fail, Redo…
Heavy use ofHeavy use of unificationunification,, backtrackingbacktracking andand recursionrecursion..
Unification (Prolog pattern matching – fromUnification (Prolog pattern matching – from WikipediaWikipedia):):
 One-time assignment (binding)
 uninst. var with atom/term/another uninst. var (aliasing) (occurs check)
 atom with the same atom
 compound with compound if top predicates and arities of the terms are
identical and if the parameters can be unified simultaneously
 We can use ‘=‘ operator to explicitly unify two terms
Backtracking:Backtracking:
 Make another choice if a choice (unif./match) failes or want to find
other answers.
 In logic prog. It is the rule rather than the exception.
 Very expensive!
Example:Example: lenlen([ ], 0).([ ], 0). lenlen(X.T, L+1) :-(X.T, L+1) :- lenlen(T,L).(T,L).
30ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Prolog’s Control RegimeProlog’s Control Regime
Prolog lang. isProlog lang. is defineddefined to useto use depth-firstdepth-first search:search:
 Top to bottom (try the clauses in order of entrance)
 Left to right
 In pure logic prog., some complete deductive algorithm such as
Robinson’s resolution algorithm must be implemented.
DFS other than BFSDFS other than BFS
 Needs much fewer memory
 Doesn’t work for an infinitely deep tree (responsibility of programmer)
Some programs may fail if clauses and subgoals are notSome programs may fail if clauses and subgoals are not
ordered correctly (pp.471-474)ordered correctly (pp.471-474)
Predictable execution ofPredictable execution of impureimpure predicates (write, nl, read,predicates (write, nl, read,
retract, asserta, assertz, …)retract, asserta, assertz, …)
31
[trace] ?- ancestor(X, cindy), sibling(X,jeffrey).[trace] ?- ancestor(X, cindy), sibling(X,jeffrey).
EventEvent DepthDepth SubgoalSubgoal
====================================================================
Call:Call: (1)(1) ancestor(X, cindy)ancestor(X, cindy)
Call:Call: (2)(2) parent(X, cindy)parent(X, cindy)
Call:Call: (3)(3) father(X, cindy)father(X, cindy)
Exit:Exit: (3)(3) father(george, cindy)father(george, cindy)
Exit:Exit: (2)(2) parent(george, cindy)parent(george, cindy)
Exit:Exit: (1)(1) ancestor(george, cindy)ancestor(george, cindy)
Call:Call: (1)(1) sibling(george, jeffrey)sibling(george, jeffrey)
Call:Call: (2)(2) mother(M, george)mother(M, george)
Exit:Exit: (2)(2) mother(alice, george)mother(alice, george)
Call:Call: (2)(2) mother(alice, jeffrey)mother(alice, jeffrey)
Exit:Exit: (2)(2) mother(alice, jeffrey)mother(alice, jeffrey)
Call:Call: (2)(2) father(F, george)father(F, george)
Exit:Exit: (2)(2) father(albert, george)father(albert, george)
Call:Call: (2)(2) father(albert, jeffrey)father(albert, jeffrey)
Exit:Exit: (2)(2) father(albert, jeffrey)father(albert, jeffrey)
Call:Call: (2)(2) george=jeffreygeorge=jeffrey
Exit:Exit: (2)(2) george=jeffreygeorge=jeffrey
Exit:Exit: (1)(1) sibling(george, jeffrey)sibling(george, jeffrey)
X = georgeX = george
YesYes
SWI Prolog
32
If we moveIf we move parent(X,Y) :- father(X,Y)parent(X,Y) :- father(X,Y) beforebefore parent(X,Y) :- mother(X,Y)parent(X,Y) :- mother(X,Y),,
we have:we have:
EventEvent DepthDepth SubgoalSubgoal
====================================================================
Call:Call: (1)(1) ancestor(X, cindy)ancestor(X, cindy)
Call:Call: (2)(2) parent(X, cindy)parent(X, cindy)
Call:Call: (3)(3) mother(X, cindy)mother(X, cindy)
Exit:Exit: (3)(3) mother(mary, cindy)mother(mary, cindy)
Exit:Exit: (2)(2) parent(mary, cindy)parent(mary, cindy)
Exit:Exit: (1)(1) ancestor(mary, cindy)ancestor(mary, cindy)
Call:Call: (1)(1) sibling(mary, jeffrey)sibling(mary, jeffrey)
Call:Call: (2)(2) mother(M, mary)mother(M, mary)
Exit:Exit: (2)(2) mother(sue, mary)mother(sue, mary)
Call:Call: (2)(2) mother(sue, jeffrey)mother(sue, jeffrey)
Fail:Fail: (2)(2) mother(sue, jeffrey)mother(sue, jeffrey)
Redo:Redo: (2)(2) mother(M, mary)mother(M, mary)
Fail:Fail: (2)(2) mother(M, mary)mother(M, mary)
Fail:Fail: (1)(1) sibling(mary, jeffrey)sibling(mary, jeffrey)
Redo:Redo: (3)(3) mother(X, cindy)mother(X, cindy)
Fail:Fail: (3)(3) mother(X, cindy)mother(X, cindy)
Redo:Redo: (2)(2) parent(X, cindy)parent(X, cindy)
……
SWI Prolog
33ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Cut!Cut! 
‘‘!’!’: Discard choice points of parent frame and frames created: Discard choice points of parent frame and frames created
after the parent frame.after the parent frame.
Always is satisfied.Always is satisfied.
Used to guarantee termination or control execution order.Used to guarantee termination or control execution order.
i.e. in the goali.e. in the goal :- p(X,a), !:- p(X,a), !
 Only produce the 1st
answer to X
 Probably only one X satisfies p and trying to find another one leads to
an infinite search!
i.e. in the rulei.e. in the rule color(X,red) :- red(X), !.color(X,red) :- red(X), !.
 Don’t try other choices of red (mentioned above) and color if X
satisfies red
 Similar to then part of a if-then-elseif
Fisher, J.R., Prolog Tutorial,
http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/contents.html
34ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Red-Green Cuts (!)Red-Green Cuts (!)
AA ‘‘greengreen’’ cutcut
 Only improves efficiency
 e.g. to avoid additional unnecessary computation
AA ‘red’‘red’ cutcut
 e.g. block what would be other consequences of
the program
 e.g. control execution order (procedural prog.)
Fisher, J.R., Prolog Tutorial,
http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/contents.html
35ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Three ExamplesThree Examples
p(a).p(a).
p(X) :- s(X), r(X).p(X) :- s(X), r(X).
p(X) :- u(X).p(X) :- u(X).
r(a). r(b).r(a). r(b).
s(a). s(b). s(c).s(a). s(b). s(c).
u(d).u(d).
:- p(X), !:- p(X), !
:- r(X), !, s(Y).:- r(X), !, s(Y).
:- r(X), s(Y), !:- r(X), s(Y), !
:- r(X), !, s(X).:- r(X), !, s(X).
part(a). part(b). part(c).part(a). part(b). part(c).
red(a). black(b).red(a). black(b).
color(P,red) :- red(P),!.color(P,red) :- red(P),!.
color(P,black) :- black(P),!.color(P,black) :- black(P),!.
color(P,unknown).color(P,unknown).
:- color(a, C).:- color(a, C).
:- color(c, C).:- color(c, C).
:- color(a, unknown).:- color(a, unknown).
Fisher, J.R., Prolog Tutorial,
http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/contents.html
max(X,Y,Y) :- Y>X, !.max(X,Y,Y) :- Y>X, !.
max(X,Y,X).max(X,Y,X).
:- max(1,2,D).:- max(1,2,D).
:- max(1,2,1).:- max(1,2,1).
See also MacLennan’s example p.476
36ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Higher-Order RulesHigher-Order Rules
Logic programming is limited to first-order logic:Logic programming is limited to first-order logic:
can’t bind variables to predicates themselves.can’t bind variables to predicates themselves.
e.g.e.g. redred (f-reduction) is illegal: (p(x,y,z) ↔ z=f(x,y))(f-reduction) is illegal: (p(x,y,z) ↔ z=f(x,y))
red(P,I,[ ],I).
red(P,I,X.L,S) :- red(P,I,L,T), P(X,T,S).
But is legal if the latter be defined as:But is legal if the latter be defined as:
red(P,I,X.L,S):- red(P,I,L,T), Q=..[P,X,T,S],
call(Q).
 What’s the difference?
37ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Higher-Order Rules (cont.)Higher-Order Rules (cont.)
In LISP, both code and data areIn LISP, both code and data are first-orderfirst-order objects,objects,
but in Prolog arenbut in Prolog aren’’t.t.
RobinsonRobinson resolution algorithmresolution algorithm is refutation completeis refutation complete
forfor first-orderfirst-order predicate logic.predicate logic.
GödelGödel’’ss incompleteness theoremincompleteness theorem: No algorithm is: No algorithm is
refutation complete forrefutation complete for higher-orderhigher-order predicate logic.predicate logic.
So, PrologSo, Prolog indirectlyindirectly supports higher-order rules.supports higher-order rules.
38ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Negative FactsNegative Facts
How to defineHow to define nonsiblingnonsibling? Logically? Logically……
nonsibling(X,Y) :- X = Y.
nonsibling(X,Y) :- mother(M1,X), mother(M2,Y), M1 = M2.
nonsibling(X,Y) :- father(F1,X), father(F2,Y), F1 = F2.
But if parents of X or Y are not in database?But if parents of X or Y are not in database?
 What is the answer of nonsibling? Can be solved by…
nonsibling(X,Y) :- no_parent(X).
nonsibling(X,Y) :- no_parent(Y).
 How to define no_parent?
39ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Negative Facts (cont.)Negative Facts (cont.)
Problem:Problem: There is noThere is no positivepositive fact expressingfact expressing
thethe absenceabsence of parent.of parent.
Cause:Cause:
 Horn clauses are limited to
 C :- P1,P2,…,Pn ≡ C holds if P1^P2^…^Pn hold.
 No conclusion if P1^P2^…^Pn don’t hold!
 If, not iff
40ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Cut-failCut-fail
Solutions:Solutions:
StatingStating allall negative facts such as no_parentnegative facts such as no_parent
 Tedious
 Error-prone
 Negative facts about sth are usually much more than positive facts
about it
““Cut-fail”Cut-fail” combinationcombination
 nonsibling(X,Y) is satisfiable if sibling(X,Y) is not (i.e. sibling(X,Y) is
unsatisfiable)
 nonsibling(X,Y) :- sibling(X,Y), !, fail.
 nonsibling(X,Y).
 how to define ‘fail’ ?!
41ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
negation :- unsatisfiablilitynegation :- unsatisfiablility
‘‘not’not’ predicatepredicate
 not(P) is satisfiable if P is not (i.e. is
unsatisfiable).
 not(P) :- call(P), !, fail.
 not(P).
 nonsibling(X,Y) :- not( sibling(X,Y) ).
IsIs ‘not’‘not’ predicate the same aspredicate the same as ‘logical‘logical
negation’negation’? (see p.484)? (see p.484)
42
Evaluation and EpilogEvaluation and Epilog
13.513.5
43ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
TopicsTopics
Logic programs areLogic programs are self-documentingself-documenting
Pure logic programsPure logic programs separateseparate logic and controllogic and control
Prolog fallsProlog falls short ofshort of logic programminglogic programming
Implementation techniques areImplementation techniques are improvingimproving
Prolog isProlog is a stepa step towardtoward nonproceduralnonprocedural
programmingprogramming
44ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Self-documentationSelf-documentation
Programming in a higher-level, …Programming in a higher-level, …
Application orientation and…Application orientation and…
TransparencyTransparency
 programs are described in terms of predicates and
individuals of the problem domain.
Promotes clear, rapid, accurate programmingPromotes clear, rapid, accurate programming
45ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Separation of Logic and ControlSeparation of Logic and Control
Simplifies programmingSimplifies programming
Correctness only deals with logicCorrectness only deals with logic
Optimization in control cannot affectOptimization in control cannot affect
correctnesscorrectness
ObeysObeys Orthogonality PrincipleOrthogonality Principle
46ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Prolog vs. Logic ProgrammingProlog vs. Logic Programming
Definite control strategyDefinite control strategy
 Programmers make explicit use of it and the result
have little to do with logic
 Reasoning about the order of events in Prolog is
comparable in difficaulty with most imperative of
conventional programming languages
CutCut doesn’t make any sense in logic!doesn’t make any sense in logic!
notnot doesn’t correspond to logical negationdoesn’t correspond to logical negation
47ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Improving EfficiencyImproving Efficiency
Prolog is far from an efficient language.Prolog is far from an efficient language.
So, it’s applications are limited to apps inSo, it’s applications are limited to apps in
which:which:
 Performance is not important
 Difficult to implement in a conventional lang.
New methods are inventedNew methods are invented
Some compilers produce code comparable toSome compilers produce code comparable to
LISPLISP
48ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Toward Nonprocedural ProgrammingToward Nonprocedural Programming
PurePure logic programs prove the possibility oflogic programs prove the possibility of
nonprocedural programming.nonprocedural programming.
InIn PrologProlog, DFS requires programmers to think in, DFS requires programmers to think in
terms ofterms of operationsoperations and their properand their proper orderingordering in timein time
(procedurally).(procedurally).
AndAnd Prolog’s control regime is moreProlog’s control regime is more unnaturalunnatural thanthan
conventional languages.conventional languages.
So,So, there is still much more important work to bethere is still much more important work to be
done before nonprocedural programming becomesdone before nonprocedural programming becomes
practicalpractical..
49ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Covered Sections of MacLennanCovered Sections of MacLennan
13.113.1
13.213.2
13.313.3
13.413.4
 except topics starting on pp. 471, 475, 477, 484,
485, 486, 488
13.513.5
50ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design
Presentation ReferencesPresentation References
Colmerauer, Alain, Philippe Roussel,Colmerauer, Alain, Philippe Roussel, The Birth of Prolog,The Birth of Prolog, Nov. 1992,Nov. 1992,
URL:URL: http://www.lim.univ-http://www.lim.univ-
mrs.fr/~colmer/ArchivesPublications/HistoireProlog/19november92.pdfmrs.fr/~colmer/ArchivesPublications/HistoireProlog/19november92.pdf
Fisher, J.R., Prolog TutorialFisher, J.R., Prolog Tutorial, 2004, URL:, 2004, URL:
http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/contents.htmlhttp://www.csupomona.edu/~jrfisher/www/prolog_tutorial/contents.html
MacLennan, Bruce J., Principles of Programming Languages: Design,MacLennan, Bruce J., Principles of Programming Languages: Design,
Evaluation and Implementation,Evaluation and Implementation, 3rd ed, Oxford University Press, 19993rd ed, Oxford University Press, 1999
Merritt, Dennis, “Prolog Under the Hood: An Honest Look”Merritt, Dennis, “Prolog Under the Hood: An Honest Look”,, PC AIPC AI
magazine, Sep/Oct 1992magazine, Sep/Oct 1992
““Unification”Unification”, Wikipedia, the free encyclopedia, 25 Sep. 2005, URL:, Wikipedia, the free encyclopedia, 25 Sep. 2005, URL:
http://en.wikipedia.org/wiki/Unificationhttp://en.wikipedia.org/wiki/Unification
51
Thank You!Thank You!
This lecture was a student lecture presented at theThis lecture was a student lecture presented at the
Electrical and Computer Engineering Department ofElectrical and Computer Engineering Department of
the University of Tehran, in Fall 2005.the University of Tehran, in Fall 2005.
Instructor: Dr. M. SirjaniInstructor: Dr. M. Sirjani

More Related Content

What's hot (20)

Ai Image Generator.pptx
Ai Image Generator.pptxAi Image Generator.pptx
Ai Image Generator.pptx
muhammadasad133521
 
AI Lecture 3 (solving problems by searching)
AI Lecture 3 (solving problems by searching)AI Lecture 3 (solving problems by searching)
AI Lecture 3 (solving problems by searching)
Tajim Md. Niamat Ullah Akhund
 
Propositional logic
Propositional logicPropositional logic
Propositional logic
Rushdi Shams
 
AI PPT-ALR_Unit-3-1.pdf
AI PPT-ALR_Unit-3-1.pdfAI PPT-ALR_Unit-3-1.pdf
AI PPT-ALR_Unit-3-1.pdf
lokesh406075
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
Mir Majid
 
Artificial Intelligence Notes Unit 1
Artificial Intelligence Notes Unit 1 Artificial Intelligence Notes Unit 1
Artificial Intelligence Notes Unit 1
DigiGurukul
 
Creating A Character in Uncharted: Drake's Fortune
Creating A Character in Uncharted: Drake's FortuneCreating A Character in Uncharted: Drake's Fortune
Creating A Character in Uncharted: Drake's Fortune
Naughty Dog
 
PROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In PrologPROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In Prolog
DataminingTools Inc
 
Code generator
Code generatorCode generator
Code generator
Tech_MX
 
Semantic Role Labeling
Semantic Role LabelingSemantic Role Labeling
Semantic Role Labeling
Marina Santini
 
NLP
NLPNLP
NLP
Girish Khanzode
 
3 d viewing
3 d viewing3 d viewing
3 d viewing
Deepak Singh
 
Graph Planning
Graph PlanningGraph Planning
Graph Planning
ahmad bassiouny
 
Chapter3 Search
Chapter3 SearchChapter3 Search
Chapter3 Search
Khiem Ho
 
Lecture: Word Sense Disambiguation
Lecture: Word Sense DisambiguationLecture: Word Sense Disambiguation
Lecture: Word Sense Disambiguation
Marina Santini
 
Recognition-of-tokens
Recognition-of-tokensRecognition-of-tokens
Recognition-of-tokens
Dattatray Gandhmal
 
Goal stack planning.ppt
Goal stack planning.pptGoal stack planning.ppt
Goal stack planning.ppt
SadagopanS
 
Chomsky & Greibach Normal Forms
Chomsky & Greibach Normal FormsChomsky & Greibach Normal Forms
Chomsky & Greibach Normal Forms
Rajendran
 
AI_ 3 & 4 Knowledge Representation issues
AI_ 3 & 4 Knowledge Representation issuesAI_ 3 & 4 Knowledge Representation issues
AI_ 3 & 4 Knowledge Representation issues
Khushali Kathiriya
 
Natural language processing
Natural language processingNatural language processing
Natural language processing
National Institute of Technology Durgapur
 
Propositional logic
Propositional logicPropositional logic
Propositional logic
Rushdi Shams
 
AI PPT-ALR_Unit-3-1.pdf
AI PPT-ALR_Unit-3-1.pdfAI PPT-ALR_Unit-3-1.pdf
AI PPT-ALR_Unit-3-1.pdf
lokesh406075
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
Mir Majid
 
Artificial Intelligence Notes Unit 1
Artificial Intelligence Notes Unit 1 Artificial Intelligence Notes Unit 1
Artificial Intelligence Notes Unit 1
DigiGurukul
 
Creating A Character in Uncharted: Drake's Fortune
Creating A Character in Uncharted: Drake's FortuneCreating A Character in Uncharted: Drake's Fortune
Creating A Character in Uncharted: Drake's Fortune
Naughty Dog
 
PROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In PrologPROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In Prolog
DataminingTools Inc
 
Code generator
Code generatorCode generator
Code generator
Tech_MX
 
Semantic Role Labeling
Semantic Role LabelingSemantic Role Labeling
Semantic Role Labeling
Marina Santini
 
Chapter3 Search
Chapter3 SearchChapter3 Search
Chapter3 Search
Khiem Ho
 
Lecture: Word Sense Disambiguation
Lecture: Word Sense DisambiguationLecture: Word Sense Disambiguation
Lecture: Word Sense Disambiguation
Marina Santini
 
Goal stack planning.ppt
Goal stack planning.pptGoal stack planning.ppt
Goal stack planning.ppt
SadagopanS
 
Chomsky & Greibach Normal Forms
Chomsky & Greibach Normal FormsChomsky & Greibach Normal Forms
Chomsky & Greibach Normal Forms
Rajendran
 
AI_ 3 & 4 Knowledge Representation issues
AI_ 3 & 4 Knowledge Representation issuesAI_ 3 & 4 Knowledge Representation issues
AI_ 3 & 4 Knowledge Representation issues
Khushali Kathiriya
 

Viewers also liked (20)

Prolog Programming : Basics
Prolog Programming : BasicsProlog Programming : Basics
Prolog Programming : Basics
Mitul Desai
 
Logic programming (1)
Logic programming (1)Logic programming (1)
Logic programming (1)
Nitesh Singh
 
Logic Programming and ILP
Logic Programming and ILPLogic Programming and ILP
Logic Programming and ILP
Pierre de Lacaze
 
Introduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in LogicIntroduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in Logic
Vishal Tandel
 
PROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In PrologPROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In Prolog
PROLOG CONTENT
 
Logic programming in python
Logic programming in pythonLogic programming in python
Logic programming in python
Pierre Carbonnelle
 
Prolog basics
Prolog basicsProlog basics
Prolog basics
shivani saluja
 
حریم خصوصی در دنیای مدرن: خواسته‌ها، چالش‌ها، و راه‌حل‌ها
حریم خصوصی در دنیای مدرن: خواسته‌ها، چالش‌ها، و راه‌حل‌هاحریم خصوصی در دنیای مدرن: خواسته‌ها، چالش‌ها، و راه‌حل‌ها
حریم خصوصی در دنیای مدرن: خواسته‌ها، چالش‌ها، و راه‌حل‌ها
Sadegh Dorri N.
 
Uncertainty in Probabilistic Trust Models
Uncertainty in Probabilistic Trust ModelsUncertainty in Probabilistic Trust Models
Uncertainty in Probabilistic Trust Models
Sadegh Dorri N.
 
ارزیابی سامانه‌های رایانه‌ای با کمک شبیه‌سازی
ارزیابی سامانه‌های رایانه‌ای با کمک شبیه‌سازیارزیابی سامانه‌های رایانه‌ای با کمک شبیه‌سازی
ارزیابی سامانه‌های رایانه‌ای با کمک شبیه‌سازی
Sadegh Dorri N.
 
Trust in the Virtual World
Trust in the Virtual WorldTrust in the Virtual World
Trust in the Virtual World
Sadegh Dorri N.
 
Scope of variables
Scope of variablesScope of variables
Scope of variables
Michael Gordon
 
Introduccion a prolog
Introduccion a prologIntroduccion a prolog
Introduccion a prolog
JeffoG92
 
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
Shahzeb Pirzada
 
Ch10 Recursion
Ch10 RecursionCh10 Recursion
Ch10 Recursion
leminhvuong
 
Prolog programming
Prolog programmingProlog programming
Prolog programming
Harry Potter
 
GeekNight: Evolution of Programming Languages
GeekNight: Evolution of Programming LanguagesGeekNight: Evolution of Programming Languages
GeekNight: Evolution of Programming Languages
Hyderabad Scalability Meetup
 
Knight’s tour algorithm
Knight’s tour algorithmKnight’s tour algorithm
Knight’s tour algorithm
Hassan Tariq
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
MOHIT DADU
 
Knight's Tour
Knight's TourKnight's Tour
Knight's Tour
Kelum Senanayake
 
Prolog Programming : Basics
Prolog Programming : BasicsProlog Programming : Basics
Prolog Programming : Basics
Mitul Desai
 
Logic programming (1)
Logic programming (1)Logic programming (1)
Logic programming (1)
Nitesh Singh
 
Introduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in LogicIntroduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in Logic
Vishal Tandel
 
PROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In PrologPROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In Prolog
PROLOG CONTENT
 
حریم خصوصی در دنیای مدرن: خواسته‌ها، چالش‌ها، و راه‌حل‌ها
حریم خصوصی در دنیای مدرن: خواسته‌ها، چالش‌ها، و راه‌حل‌هاحریم خصوصی در دنیای مدرن: خواسته‌ها، چالش‌ها، و راه‌حل‌ها
حریم خصوصی در دنیای مدرن: خواسته‌ها، چالش‌ها، و راه‌حل‌ها
Sadegh Dorri N.
 
Uncertainty in Probabilistic Trust Models
Uncertainty in Probabilistic Trust ModelsUncertainty in Probabilistic Trust Models
Uncertainty in Probabilistic Trust Models
Sadegh Dorri N.
 
ارزیابی سامانه‌های رایانه‌ای با کمک شبیه‌سازی
ارزیابی سامانه‌های رایانه‌ای با کمک شبیه‌سازیارزیابی سامانه‌های رایانه‌ای با کمک شبیه‌سازی
ارزیابی سامانه‌های رایانه‌ای با کمک شبیه‌سازی
Sadegh Dorri N.
 
Trust in the Virtual World
Trust in the Virtual WorldTrust in the Virtual World
Trust in the Virtual World
Sadegh Dorri N.
 
Introduccion a prolog
Introduccion a prologIntroduccion a prolog
Introduccion a prolog
JeffoG92
 
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
Shahzeb Pirzada
 
Prolog programming
Prolog programmingProlog programming
Prolog programming
Harry Potter
 
Knight’s tour algorithm
Knight’s tour algorithmKnight’s tour algorithm
Knight’s tour algorithm
Hassan Tariq
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
MOHIT DADU
 
Ad

Similar to Logic Programming and Prolog (20)

Introduction to Prolog (PROramming in LOGic)
Introduction to Prolog (PROramming in LOGic)Introduction to Prolog (PROramming in LOGic)
Introduction to Prolog (PROramming in LOGic)
Ahmed Gad
 
Prolog final
Prolog finalProlog final
Prolog final
Hassaan Ahmad
 
Introduction to prolog
Introduction to prologIntroduction to prolog
Introduction to prolog
Rakhi Sinha
 
Prolog & lisp
Prolog & lispProlog & lisp
Prolog & lisp
Ismail El Gayar
 
PROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOG
PROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOG
PROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOG
Kdas004
 
Unit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit
Unit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnitUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit
Unit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit
ManishYadav243888
 
ICS1019.pdf
ICS1019.pdfICS1019.pdf
ICS1019.pdf
Matt Montebello
 
PROLOG in artificial intelligence(Basic of pprolog)).pdf
PROLOG in artificial intelligence(Basic of pprolog)).pdfPROLOG in artificial intelligence(Basic of pprolog)).pdf
PROLOG in artificial intelligence(Basic of pprolog)).pdf
sakshamkumar272464
 
Chaps 1-3-ai-prolog
Chaps 1-3-ai-prologChaps 1-3-ai-prolog
Chaps 1-3-ai-prolog
juanpaperez1234
 
Chaps 1-3-ai-prolog
Chaps 1-3-ai-prologChaps 1-3-ai-prolog
Chaps 1-3-ai-prolog
saru40
 
Ics1019 ics5003
Ics1019 ics5003Ics1019 ics5003
Ics1019 ics5003
Matt Montebello
 
ProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) IntroductionProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) Introduction
wahab khan
 
Prolog_Programminvfygugy7gtugbugtg_Notes.docx
Prolog_Programminvfygugy7gtugbugtg_Notes.docxProlog_Programminvfygugy7gtugbugtg_Notes.docx
Prolog_Programminvfygugy7gtugbugtg_Notes.docx
ap04944
 
10 logic+programming+with+prolog
10 logic+programming+with+prolog10 logic+programming+with+prolog
10 logic+programming+with+prolog
baran19901990
 
2 Prolog L 1 V2.ppt
2 Prolog L 1 V2.ppt2 Prolog L 1 V2.ppt
2 Prolog L 1 V2.ppt
AbobakrMohammedAbdoS1
 
Prolog (present)
Prolog (present) Prolog (present)
Prolog (present)
Melody Joey
 
Ics1019 ics5003
Ics1019 ics5003Ics1019 ics5003
Ics1019 ics5003
Matt Montebello
 
Plc part 4
Plc  part 4Plc  part 4
Plc part 4
Taymoor Nazmy
 
________ ________1.ppt
________ ________1.ppt________ ________1.ppt
________ ________1.ppt
SamiAAli44
 
Prolog,Prolog Programming IN AI.pdf
Prolog,Prolog Programming IN AI.pdfProlog,Prolog Programming IN AI.pdf
Prolog,Prolog Programming IN AI.pdf
CS With Logic
 
Introduction to Prolog (PROramming in LOGic)
Introduction to Prolog (PROramming in LOGic)Introduction to Prolog (PROramming in LOGic)
Introduction to Prolog (PROramming in LOGic)
Ahmed Gad
 
Introduction to prolog
Introduction to prologIntroduction to prolog
Introduction to prolog
Rakhi Sinha
 
PROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOG
PROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOG
PROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOG
Kdas004
 
Unit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit
Unit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnitUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit
Unit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit
ManishYadav243888
 
PROLOG in artificial intelligence(Basic of pprolog)).pdf
PROLOG in artificial intelligence(Basic of pprolog)).pdfPROLOG in artificial intelligence(Basic of pprolog)).pdf
PROLOG in artificial intelligence(Basic of pprolog)).pdf
sakshamkumar272464
 
Chaps 1-3-ai-prolog
Chaps 1-3-ai-prologChaps 1-3-ai-prolog
Chaps 1-3-ai-prolog
saru40
 
ProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) IntroductionProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) Introduction
wahab khan
 
Prolog_Programminvfygugy7gtugbugtg_Notes.docx
Prolog_Programminvfygugy7gtugbugtg_Notes.docxProlog_Programminvfygugy7gtugbugtg_Notes.docx
Prolog_Programminvfygugy7gtugbugtg_Notes.docx
ap04944
 
10 logic+programming+with+prolog
10 logic+programming+with+prolog10 logic+programming+with+prolog
10 logic+programming+with+prolog
baran19901990
 
Prolog (present)
Prolog (present) Prolog (present)
Prolog (present)
Melody Joey
 
________ ________1.ppt
________ ________1.ppt________ ________1.ppt
________ ________1.ppt
SamiAAli44
 
Prolog,Prolog Programming IN AI.pdf
Prolog,Prolog Programming IN AI.pdfProlog,Prolog Programming IN AI.pdf
Prolog,Prolog Programming IN AI.pdf
CS With Logic
 
Ad

More from Sadegh Dorri N. (11)

فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین (شانزدهمین کنفرانس مهندسی ص...
فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین (شانزدهمین کنفرانس مهندسی ص...فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین (شانزدهمین کنفرانس مهندسی ص...
فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین (شانزدهمین کنفرانس مهندسی ص...
Sadegh Dorri N.
 
معرفی آزمایشگاه زنجیره بلوک و زمینه‌های پژوهشی
معرفی آزمایشگاه زنجیره بلوک و زمینه‌های پژوهشیمعرفی آزمایشگاه زنجیره بلوک و زمینه‌های پژوهشی
معرفی آزمایشگاه زنجیره بلوک و زمینه‌های پژوهشی
Sadegh Dorri N.
 
فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین
فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمینفناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین
فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین
Sadegh Dorri N.
 
Smart Contract Security
Smart Contract SecuritySmart Contract Security
Smart Contract Security
Sadegh Dorri N.
 
Blockchain-based Applications
Blockchain-based ApplicationsBlockchain-based Applications
Blockchain-based Applications
Sadegh Dorri N.
 
Varieties of Blockchains
Varieties of BlockchainsVarieties of Blockchains
Varieties of Blockchains
Sadegh Dorri N.
 
Bitcoin Mechanics
Bitcoin MechanicsBitcoin Mechanics
Bitcoin Mechanics
Sadegh Dorri N.
 
Introduction to Bitcoin
Introduction to BitcoinIntroduction to Bitcoin
Introduction to Bitcoin
Sadegh Dorri N.
 
Lightweight Virtualization in Linux
Lightweight Virtualization in LinuxLightweight Virtualization in Linux
Lightweight Virtualization in Linux
Sadegh Dorri N.
 
کنترل دسترسی بر مبنای اعتماد و آگاه از مخاطره در توری
کنترل دسترسی بر مبنای اعتماد و آگاه از مخاطره در توریکنترل دسترسی بر مبنای اعتماد و آگاه از مخاطره در توری
کنترل دسترسی بر مبنای اعتماد و آگاه از مخاطره در توری
Sadegh Dorri N.
 
مهندسی حریم خصوصی
مهندسی حریم خصوصیمهندسی حریم خصوصی
مهندسی حریم خصوصی
Sadegh Dorri N.
 
فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین (شانزدهمین کنفرانس مهندسی ص...
فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین (شانزدهمین کنفرانس مهندسی ص...فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین (شانزدهمین کنفرانس مهندسی ص...
فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین (شانزدهمین کنفرانس مهندسی ص...
Sadegh Dorri N.
 
معرفی آزمایشگاه زنجیره بلوک و زمینه‌های پژوهشی
معرفی آزمایشگاه زنجیره بلوک و زمینه‌های پژوهشیمعرفی آزمایشگاه زنجیره بلوک و زمینه‌های پژوهشی
معرفی آزمایشگاه زنجیره بلوک و زمینه‌های پژوهشی
Sadegh Dorri N.
 
فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین
فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمینفناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین
فناوری زنجیره بلوک و کاربردهای آن در زنجیره تأمین
Sadegh Dorri N.
 
Blockchain-based Applications
Blockchain-based ApplicationsBlockchain-based Applications
Blockchain-based Applications
Sadegh Dorri N.
 
Varieties of Blockchains
Varieties of BlockchainsVarieties of Blockchains
Varieties of Blockchains
Sadegh Dorri N.
 
Lightweight Virtualization in Linux
Lightweight Virtualization in LinuxLightweight Virtualization in Linux
Lightweight Virtualization in Linux
Sadegh Dorri N.
 
کنترل دسترسی بر مبنای اعتماد و آگاه از مخاطره در توری
کنترل دسترسی بر مبنای اعتماد و آگاه از مخاطره در توریکنترل دسترسی بر مبنای اعتماد و آگاه از مخاطره در توری
کنترل دسترسی بر مبنای اعتماد و آگاه از مخاطره در توری
Sadegh Dorri N.
 
مهندسی حریم خصوصی
مهندسی حریم خصوصیمهندسی حریم خصوصی
مهندسی حریم خصوصی
Sadegh Dorri N.
 

Recently uploaded (20)

Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
sebastianku31
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
Webinar On Steel Melting IIF of steel for rdso
Webinar  On Steel  Melting IIF of steel for rdsoWebinar  On Steel  Melting IIF of steel for rdso
Webinar On Steel Melting IIF of steel for rdso
KapilParyani3
 
Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
ANFIS Models with Subtractive Clustering and Fuzzy C-Mean Clustering Techniqu...
ANFIS Models with Subtractive Clustering and Fuzzy C-Mean Clustering Techniqu...ANFIS Models with Subtractive Clustering and Fuzzy C-Mean Clustering Techniqu...
ANFIS Models with Subtractive Clustering and Fuzzy C-Mean Clustering Techniqu...
Journal of Soft Computing in Civil Engineering
 
22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank
Guru Nanak Technical Institutions
 
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
ijccmsjournal
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Software Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance OptimizationSoftware Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance Optimization
kiwoong (daniel) kim
 
First Review PPT gfinal gyft ftu liu yrfut go
First Review PPT gfinal gyft  ftu liu yrfut goFirst Review PPT gfinal gyft  ftu liu yrfut go
First Review PPT gfinal gyft ftu liu yrfut go
Sowndarya6
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)
jaresjournal868
 
Presentación Tomografía Axial Computarizada
Presentación Tomografía Axial ComputarizadaPresentación Tomografía Axial Computarizada
Presentación Tomografía Axial Computarizada
Juliana Ovalle Jiménez
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
sebastianku31
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
Webinar On Steel Melting IIF of steel for rdso
Webinar  On Steel  Melting IIF of steel for rdsoWebinar  On Steel  Melting IIF of steel for rdso
Webinar On Steel Melting IIF of steel for rdso
KapilParyani3
 
Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
ijccmsjournal
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Software Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance OptimizationSoftware Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance Optimization
kiwoong (daniel) kim
 
First Review PPT gfinal gyft ftu liu yrfut go
First Review PPT gfinal gyft  ftu liu yrfut goFirst Review PPT gfinal gyft  ftu liu yrfut go
First Review PPT gfinal gyft ftu liu yrfut go
Sowndarya6
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)
jaresjournal868
 
Presentación Tomografía Axial Computarizada
Presentación Tomografía Axial ComputarizadaPresentación Tomografía Axial Computarizada
Presentación Tomografía Axial Computarizada
Juliana Ovalle Jiménez
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 

Logic Programming and Prolog

  • 1. 1 Logic ProgrammingLogic Programming And PrologAnd Prolog MacLennan - Chapter 13MacLennan - Chapter 13 ECE Department of Tehran UniversityECE Department of Tehran University Programming Language Design CourseProgramming Language Design Course Student LectureStudent Lecture Sadegh Dorri Nogoorani (http://ce.sharif.edu/~dorri)Sadegh Dorri Nogoorani (http://ce.sharif.edu/~dorri)
  • 2. 2ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design 55thth -Generation Languages-Generation Languages Declarative (nonprocedural)Declarative (nonprocedural)  Functional Programming  Logic Programming ImperativeImperative  Object Oriented Programming
  • 3. 3ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Nonprocedural ProgrammingNonprocedural Programming Sorting procedurally:Sorting procedurally: 1. Find the min in the remained numbers. 2. Swap it with the first number. 3. Repeat steps 1,2 until no number remains. Sorting nonprocedurally:Sorting nonprocedurally: 1. B is a sorting of A ↔ B is a permutation of A and B is ordered. 2. B is ordered ↔ for each i<j: B[i] ≤ B[j] Which isWhich is higher levelhigher level??
  • 4. 4ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Automated Theorem ProvingAutomated Theorem Proving A.T.P:A.T.P: Developing programs that can construct formal proofsDeveloping programs that can construct formal proofs of propositions stated in a symbolic language.of propositions stated in a symbolic language. ConstructConstruct the desired result to prove its existence (mostthe desired result to prove its existence (most A.T.P.’s).A.T.P.’s). InIn Logic ProgrammingLogic Programming,, programs are expressed in the form ofprograms are expressed in the form of propositions and the theorem prover constructs the result(s).propositions and the theorem prover constructs the result(s). J. A. Robinson: A program is a theory (in some logic) andJ. A. Robinson: A program is a theory (in some logic) and computation is deduction from the theory.computation is deduction from the theory.
  • 5. 5ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Programming In Logic (Prolog)Programming In Logic (Prolog) Developed inDeveloped in Groupe d’Intelligence ArtificielleGroupe d’Intelligence Artificielle (GIA)(GIA) of the University of Marseilles (early 70s) to processof the University of Marseilles (early 70s) to process a natural language (French).a natural language (French). Interpreters: Algol-W (72), FORTRAN (73), PascalInterpreters: Algol-W (72), FORTRAN (73), Pascal (76), Implemented on many platforms (Now)(76), Implemented on many platforms (Now) Application in AI since mid-70sApplication in AI since mid-70s Successor to LISP for AI appsSuccessor to LISP for AI apps Not standardized (but has ISO standard now)Not standardized (but has ISO standard now)
  • 7. 7 parentparent(X,Y) :-(X,Y) :- fatherfather(X,Y).(X,Y). parentparent(X,Y) :-(X,Y) :- mothermother(X,Y).(X,Y). grandparentgrandparent(X,Z) :-(X,Z) :- parentparent(X,Y),(X,Y), parentparent(Y,Z).(Y,Z). ancestorancestor(X,Z) :-(X,Z) :- parentparent(X,Z).(X,Z). ancestorancestor(X,Y) :-(X,Y) :- parentparent(X,Y),(X,Y), ancestorancestor(Y,Z).(Y,Z). siblingsibling(X,Y) :-(X,Y) :- mothermother(M,X),(M,X), mothermother(M,Y),(M,Y), fatherfather(F,X),(F,X), fatherfather(F,Y), X = Y.(F,Y), X = Y. cousincousin(X,Y) :-(X,Y) :- parentparent(U,X),(U,X), parentparent(V,Y),(V,Y), siblingsibling(U,V).(U,V). fatherfather(albert, jeffrey).(albert, jeffrey). mothermother(alice, jeffrey).(alice, jeffrey). fatherfather(albert, george).(albert, george). mothermother(alice, george).(alice, george). fatherfather(john, mary).(john, mary). mothermother(sue, mary).(sue, mary). fatherfather(george, cindy).(george, cindy). mothermother(mary, cindy).(mary, cindy). fatherfather(george, victor).(george, victor). mothermother(mary, victor).(mary, victor).
  • 8. 8 ?-?- [kinship].[kinship]. % kinship compiled 0.00 sec, 3,016 bytes% kinship compiled 0.00 sec, 3,016 bytes YesYes ?-?- ancestor(X, cindy), sibling(X, jeffrey).ancestor(X, cindy), sibling(X, jeffrey). X = georgeX = george ↵↵ YesYes ?-?- grandparent(albert, victor).grandparent(albert, victor). YesYes ?-?- cousin(alice, john).cousin(alice, john). NoNo ?-?- sibling(A,B).sibling(A,B). A = jeffrey, B = georgeA = jeffrey, B = george ;; ↵↵ A = george, B = jeffreyA = george, B = jeffrey ;; ↵↵ A = cindy, B = victorA = cindy, B = victor ;; ↵↵ A = victor, B = cindyA = victor, B = cindy ;; ↵↵ NoNo SWI Prolog
  • 9. 9ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design ClausesClauses Programs are constructed from A number ofPrograms are constructed from A number of clausesclauses: <head>: <head> :-:- <body><body> Clauses have three forms:Clauses have three forms:  hypotheses (facts)  conditions (rules)  goals Both <headBoth <head>> and <body> are composed ofand <body> are composed of relationshipsrelationships (also called(also called predicationspredications oror literalsliterals)) assertions (database) questions
  • 10. 10ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design RelationshipsRelationships Represent properties of and relations among theRepresent properties of and relations among the individualsindividuals A relationship is application of aA relationship is application of a predicatepredicate to one orto one or moremore termsterms Terms:Terms:  atoms (or constants): john, 25, …  variables (begin with uppercase letters): X, …  compounds Horn clause formHorn clause form:: At most one relationship inAt most one relationship in <head><head>
  • 11. 11ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Compound TermsCompound Terms It isIt is moremore convenient to describe individuals withoutconvenient to describe individuals without giving them names (giving them names (expressionsexpressions oror compoundscompounds asas terms).terms). usingusing functorsfunctors (tags):(tags): d(X, plus(U,V), plus(DU,DV)) :- d(X,U,DU), d(X,V,DV). or usingor using infix functorsinfix functors:: d(X, U+V, DU+DV) :- d(X,U,DU), d(X,V,DV). instead ofinstead of d(X,W,Z) :- sum(U,V,W), d(X,U,DU), d(X,V,DV), sum(DU,DV,Z). with less readability and some other things…with less readability and some other things…
  • 13. 13ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Primitives and ConstructorsPrimitives and Constructors FewFew primitives andprimitives and NoNo constructors.constructors. Data types and data structures are definedData types and data structures are defined implicitlyimplicitly by theirby their propertiesproperties..
  • 14. 14ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Example (datatype)Example (datatype) Natural number arithmeticNatural number arithmetic sum(succ(X), Y, succ(Z)) :- sum(X,Y,Z). sum(0,X,X). dif(X,Y,Z) :- sum(Z,Y,X). :-sum(succ(succ(0)),succ(succ(succ(0))),A). A = succ(succ(succ(succ(succ(0))))) Very inefficient! (Why such a decision?)Very inefficient! (Why such a decision?) Use ofUse of ‘is’‘is’ operator (unidirectional)operator (unidirectional)
  • 15. 15ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design PrinciplesPrinciples SimplicitySimplicity  Small number of built-in data types and operations RegularityRegularity  Uniform treatment of all data types as predicates and terms
  • 16. 16ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Data StructuresData Structures Compound termsCompound terms can represent data structurescan represent data structures Example:Example: ListsLists in LISPin LISP (car (cons X L)) = X (cdr (cons X L)) = L (cons (car L) (cdr L)) = L, for nonnull L
  • 17. 17ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Lists in PrologLists in Prolog Using compound terms:Using compound terms: car( cons(X,L), X). cdr( cons(X,L), L). list(nil). list(cons(X,L)) :- list(L). null(nil). What about null(L)?What about null(L)? How to accomplish (car (consHow to accomplish (car (cons ‘‘(a b)(a b) ‘‘(c d)))?(c d)))?
  • 18. 18ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Some Syntactic SugarSome Syntactic Sugar UsingUsing ‘.’‘.’ infix functor (in some systems)infix functor (in some systems) instead of cons:instead of cons:  Clauses? Most Prolog systems allow the abbreviation:Most Prolog systems allow the abbreviation:  [X1, X2, …, Xn] = X1. X2. … .Xn.nil  [ ] = nil  ‘.’ is right associative!
  • 19. 19ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Component SelectionComponent Selection Implicitly done byImplicitly done by pattern matchingpattern matching ((unificationunification).). append( [ ], L, L). append( X.P, L, X.Q) :- append(P,L,Q). Compare with LISP append:Compare with LISP append: (defun append (M L) (if (null M) L (cons (car M) (append (cdr M) L)) )) Taking apartTaking apart in terms ofin terms of putting togetherputting together!!  What X and P are cons’d to create M?  What number do I add to 3 to get 5 (instead of 5-3) Efficient!?Efficient!?
  • 20. 20ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Complex StructuresComplex Structures A tree using lists (in LISP):A tree using lists (in LISP):  (times (plus x y) (plus y 1)) Using compound terms directly (as records):Using compound terms directly (as records):  times(plus(x, y), plus(y, 1)) Using predicates directly:Using predicates directly:  sum(x, y, t1).  sum(y, 1, t2).  prod(t1, t2, t3). Which isWhich is betterbetter??
  • 21. 21ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Why Not Predicates?Why Not Predicates? Symbolic differentiation using predicateSymbolic differentiation using predicate structured expressions:structured expressions: d(X,W,Z) :- sum(U,V,W), d(X,Y,DU), d(X,V,DV), sum(DU,DV,Z). d(X,W,Z) :- prod(U,V,W), d(X,U,DU), d(X,V,DV), prod(DU,V,A), prod(U,DV,B), sum(A,B,Z). d(X,X,1). d(X,C,0) :- atomic(C), C = X.
  • 22. 22ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Why Not Predicates? (cont.)Why Not Predicates? (cont.) Waste use of intermediate (temporary)Waste use of intermediate (temporary) variablesvariables Less readabilityLess readability Unexpected answers!Unexpected answers! sum(x,1,z). :- d(x,z,D). No  Why? What did you expect?  How to correct it?
  • 23. 23ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Closed World ModelClosed World Model AllAll that is true is what can bethat is true is what can be provedproved on the basis of the factson the basis of the facts and rules in the database.and rules in the database. Very reasonable inVery reasonable in object-orientedobject-oriented apps (modeling a real orapps (modeling a real or imagined world)imagined world)  All existing objects are defined.  No object have a given property which cannot be found in db. Not suitable forNot suitable for mathematical problemsmathematical problems (Why?)(Why?)  An object is generally take to exist if its existance doesn’t contradict the axioms. PredicatesPredicates are better for OO-relationships,are better for OO-relationships, CompoundsCompounds forfor mathematical ones (Why?)mathematical ones (Why?)  We cannot assume existance of 1+0 whenever needed.
  • 24. 24ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design An Argument!An Argument! What’s the answer?What’s the answer? equal(X,X). :- equal(f(Y),Y). ? What’s theWhat’s the logicallogical meaning? (meaning? (occurs checkoccurs check)) AnyAny otherother meaning?meaning? Can it be represented in aCan it be represented in a finite amountfinite amount ofof memory?memory? Should weShould we detectdetect it?it?
  • 26. 26ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Algorithm = Logic + ControlAlgorithm = Logic + Control N. Wirth:N. Wirth: Program = data structure + algorithmProgram = data structure + algorithm R. Kowalski:R. Kowalski: Algorithm = logic + controlAlgorithm = logic + control In conventional programming:In conventional programming:  Logic of a program is closely related to its control  A change in order of statements alters the meaning of program In (pure) logic programming:In (pure) logic programming:  Logic (logic phase) is determined by logical interrelationships of the clauses not their order.  Control (control phase) affects the order in which actions occur in time and only affects the efficiency of programs. Orthogonality PrincipleOrthogonality Principle
  • 27. 27ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Top-Down vs. Bottom-Up ControlTop-Down vs. Bottom-Up Control Top-down ≈Top-down ≈ RecursionRecursion::  Try to reach the hypotheses from the goal. Bottom-up ≈Bottom-up ≈ IterationIteration::  Try to reach the goal from the hypotheses. Hybrid:Hybrid:  Work from both the goals and the hypotheses and try to meet in the middle. Which one is better?Which one is better? :- fib(3, F).:- fib(3, F). N=3, M=2, K=1,N=3, M=2, K=1, F=G+HF=G+H :- fib(2,F).:- fib(2,F). N=2, M=1, k=0,N=2, M=1, k=0, F=G+HF=G+H :- fib(1,F).:- fib(1,F). F=1F=1 :- fib(1,F).:- fib(1,F). F=1F=1 :- fib(1,1).:- fib(1,1). :- fib(0,F).:- fib(0,F). F=1F=1 :- fib(1,1).:- fib(1,1). :- fib(0,1).:- fib(0,1). fib(0,1). fib(1,1). fib(N,F) :- N=M+1, M=K+1, fib(M,G), fib(K,H), F=G+H, N>1.
  • 28. 28ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Procedural InterpretationProcedural Interpretation We have seenWe have seen logicallogical andand recordrecord (data structure)(data structure) interpretationsinterpretations.. Clauses can also be viewed asClauses can also be viewed as procedure invocationsprocedure invocations::  <head>: proc. definition  <body>: proc. body (a series of proc. calls)  Multiple definitions: branches of a conditional (case)  fib() example… Procedure calls can be executed in any order or evenProcedure calls can be executed in any order or even concurrently! (pure logic)concurrently! (pure logic) Input/Output params are not distinguished!Input/Output params are not distinguished!  fib(3,3) ↔ true. fib(3,F) ↔ F=3. fib(N,3) ↔ N=3. fib(N,F) ↔ ?
  • 29. 29ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Unify, Fail, Redo…Unify, Fail, Redo… Heavy use ofHeavy use of unificationunification,, backtrackingbacktracking andand recursionrecursion.. Unification (Prolog pattern matching – fromUnification (Prolog pattern matching – from WikipediaWikipedia):):  One-time assignment (binding)  uninst. var with atom/term/another uninst. var (aliasing) (occurs check)  atom with the same atom  compound with compound if top predicates and arities of the terms are identical and if the parameters can be unified simultaneously  We can use ‘=‘ operator to explicitly unify two terms Backtracking:Backtracking:  Make another choice if a choice (unif./match) failes or want to find other answers.  In logic prog. It is the rule rather than the exception.  Very expensive! Example:Example: lenlen([ ], 0).([ ], 0). lenlen(X.T, L+1) :-(X.T, L+1) :- lenlen(T,L).(T,L).
  • 30. 30ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Prolog’s Control RegimeProlog’s Control Regime Prolog lang. isProlog lang. is defineddefined to useto use depth-firstdepth-first search:search:  Top to bottom (try the clauses in order of entrance)  Left to right  In pure logic prog., some complete deductive algorithm such as Robinson’s resolution algorithm must be implemented. DFS other than BFSDFS other than BFS  Needs much fewer memory  Doesn’t work for an infinitely deep tree (responsibility of programmer) Some programs may fail if clauses and subgoals are notSome programs may fail if clauses and subgoals are not ordered correctly (pp.471-474)ordered correctly (pp.471-474) Predictable execution ofPredictable execution of impureimpure predicates (write, nl, read,predicates (write, nl, read, retract, asserta, assertz, …)retract, asserta, assertz, …)
  • 31. 31 [trace] ?- ancestor(X, cindy), sibling(X,jeffrey).[trace] ?- ancestor(X, cindy), sibling(X,jeffrey). EventEvent DepthDepth SubgoalSubgoal ==================================================================== Call:Call: (1)(1) ancestor(X, cindy)ancestor(X, cindy) Call:Call: (2)(2) parent(X, cindy)parent(X, cindy) Call:Call: (3)(3) father(X, cindy)father(X, cindy) Exit:Exit: (3)(3) father(george, cindy)father(george, cindy) Exit:Exit: (2)(2) parent(george, cindy)parent(george, cindy) Exit:Exit: (1)(1) ancestor(george, cindy)ancestor(george, cindy) Call:Call: (1)(1) sibling(george, jeffrey)sibling(george, jeffrey) Call:Call: (2)(2) mother(M, george)mother(M, george) Exit:Exit: (2)(2) mother(alice, george)mother(alice, george) Call:Call: (2)(2) mother(alice, jeffrey)mother(alice, jeffrey) Exit:Exit: (2)(2) mother(alice, jeffrey)mother(alice, jeffrey) Call:Call: (2)(2) father(F, george)father(F, george) Exit:Exit: (2)(2) father(albert, george)father(albert, george) Call:Call: (2)(2) father(albert, jeffrey)father(albert, jeffrey) Exit:Exit: (2)(2) father(albert, jeffrey)father(albert, jeffrey) Call:Call: (2)(2) george=jeffreygeorge=jeffrey Exit:Exit: (2)(2) george=jeffreygeorge=jeffrey Exit:Exit: (1)(1) sibling(george, jeffrey)sibling(george, jeffrey) X = georgeX = george YesYes SWI Prolog
  • 32. 32 If we moveIf we move parent(X,Y) :- father(X,Y)parent(X,Y) :- father(X,Y) beforebefore parent(X,Y) :- mother(X,Y)parent(X,Y) :- mother(X,Y),, we have:we have: EventEvent DepthDepth SubgoalSubgoal ==================================================================== Call:Call: (1)(1) ancestor(X, cindy)ancestor(X, cindy) Call:Call: (2)(2) parent(X, cindy)parent(X, cindy) Call:Call: (3)(3) mother(X, cindy)mother(X, cindy) Exit:Exit: (3)(3) mother(mary, cindy)mother(mary, cindy) Exit:Exit: (2)(2) parent(mary, cindy)parent(mary, cindy) Exit:Exit: (1)(1) ancestor(mary, cindy)ancestor(mary, cindy) Call:Call: (1)(1) sibling(mary, jeffrey)sibling(mary, jeffrey) Call:Call: (2)(2) mother(M, mary)mother(M, mary) Exit:Exit: (2)(2) mother(sue, mary)mother(sue, mary) Call:Call: (2)(2) mother(sue, jeffrey)mother(sue, jeffrey) Fail:Fail: (2)(2) mother(sue, jeffrey)mother(sue, jeffrey) Redo:Redo: (2)(2) mother(M, mary)mother(M, mary) Fail:Fail: (2)(2) mother(M, mary)mother(M, mary) Fail:Fail: (1)(1) sibling(mary, jeffrey)sibling(mary, jeffrey) Redo:Redo: (3)(3) mother(X, cindy)mother(X, cindy) Fail:Fail: (3)(3) mother(X, cindy)mother(X, cindy) Redo:Redo: (2)(2) parent(X, cindy)parent(X, cindy) …… SWI Prolog
  • 33. 33ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Cut!Cut!  ‘‘!’!’: Discard choice points of parent frame and frames created: Discard choice points of parent frame and frames created after the parent frame.after the parent frame. Always is satisfied.Always is satisfied. Used to guarantee termination or control execution order.Used to guarantee termination or control execution order. i.e. in the goali.e. in the goal :- p(X,a), !:- p(X,a), !  Only produce the 1st answer to X  Probably only one X satisfies p and trying to find another one leads to an infinite search! i.e. in the rulei.e. in the rule color(X,red) :- red(X), !.color(X,red) :- red(X), !.  Don’t try other choices of red (mentioned above) and color if X satisfies red  Similar to then part of a if-then-elseif Fisher, J.R., Prolog Tutorial, http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/contents.html
  • 34. 34ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Red-Green Cuts (!)Red-Green Cuts (!) AA ‘‘greengreen’’ cutcut  Only improves efficiency  e.g. to avoid additional unnecessary computation AA ‘red’‘red’ cutcut  e.g. block what would be other consequences of the program  e.g. control execution order (procedural prog.) Fisher, J.R., Prolog Tutorial, http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/contents.html
  • 35. 35ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Three ExamplesThree Examples p(a).p(a). p(X) :- s(X), r(X).p(X) :- s(X), r(X). p(X) :- u(X).p(X) :- u(X). r(a). r(b).r(a). r(b). s(a). s(b). s(c).s(a). s(b). s(c). u(d).u(d). :- p(X), !:- p(X), ! :- r(X), !, s(Y).:- r(X), !, s(Y). :- r(X), s(Y), !:- r(X), s(Y), ! :- r(X), !, s(X).:- r(X), !, s(X). part(a). part(b). part(c).part(a). part(b). part(c). red(a). black(b).red(a). black(b). color(P,red) :- red(P),!.color(P,red) :- red(P),!. color(P,black) :- black(P),!.color(P,black) :- black(P),!. color(P,unknown).color(P,unknown). :- color(a, C).:- color(a, C). :- color(c, C).:- color(c, C). :- color(a, unknown).:- color(a, unknown). Fisher, J.R., Prolog Tutorial, http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/contents.html max(X,Y,Y) :- Y>X, !.max(X,Y,Y) :- Y>X, !. max(X,Y,X).max(X,Y,X). :- max(1,2,D).:- max(1,2,D). :- max(1,2,1).:- max(1,2,1). See also MacLennan’s example p.476
  • 36. 36ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Higher-Order RulesHigher-Order Rules Logic programming is limited to first-order logic:Logic programming is limited to first-order logic: can’t bind variables to predicates themselves.can’t bind variables to predicates themselves. e.g.e.g. redred (f-reduction) is illegal: (p(x,y,z) ↔ z=f(x,y))(f-reduction) is illegal: (p(x,y,z) ↔ z=f(x,y)) red(P,I,[ ],I). red(P,I,X.L,S) :- red(P,I,L,T), P(X,T,S). But is legal if the latter be defined as:But is legal if the latter be defined as: red(P,I,X.L,S):- red(P,I,L,T), Q=..[P,X,T,S], call(Q).  What’s the difference?
  • 37. 37ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Higher-Order Rules (cont.)Higher-Order Rules (cont.) In LISP, both code and data areIn LISP, both code and data are first-orderfirst-order objects,objects, but in Prolog arenbut in Prolog aren’’t.t. RobinsonRobinson resolution algorithmresolution algorithm is refutation completeis refutation complete forfor first-orderfirst-order predicate logic.predicate logic. GödelGödel’’ss incompleteness theoremincompleteness theorem: No algorithm is: No algorithm is refutation complete forrefutation complete for higher-orderhigher-order predicate logic.predicate logic. So, PrologSo, Prolog indirectlyindirectly supports higher-order rules.supports higher-order rules.
  • 38. 38ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Negative FactsNegative Facts How to defineHow to define nonsiblingnonsibling? Logically? Logically…… nonsibling(X,Y) :- X = Y. nonsibling(X,Y) :- mother(M1,X), mother(M2,Y), M1 = M2. nonsibling(X,Y) :- father(F1,X), father(F2,Y), F1 = F2. But if parents of X or Y are not in database?But if parents of X or Y are not in database?  What is the answer of nonsibling? Can be solved by… nonsibling(X,Y) :- no_parent(X). nonsibling(X,Y) :- no_parent(Y).  How to define no_parent?
  • 39. 39ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Negative Facts (cont.)Negative Facts (cont.) Problem:Problem: There is noThere is no positivepositive fact expressingfact expressing thethe absenceabsence of parent.of parent. Cause:Cause:  Horn clauses are limited to  C :- P1,P2,…,Pn ≡ C holds if P1^P2^…^Pn hold.  No conclusion if P1^P2^…^Pn don’t hold!  If, not iff
  • 40. 40ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Cut-failCut-fail Solutions:Solutions: StatingStating allall negative facts such as no_parentnegative facts such as no_parent  Tedious  Error-prone  Negative facts about sth are usually much more than positive facts about it ““Cut-fail”Cut-fail” combinationcombination  nonsibling(X,Y) is satisfiable if sibling(X,Y) is not (i.e. sibling(X,Y) is unsatisfiable)  nonsibling(X,Y) :- sibling(X,Y), !, fail.  nonsibling(X,Y).  how to define ‘fail’ ?!
  • 41. 41ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design negation :- unsatisfiablilitynegation :- unsatisfiablility ‘‘not’not’ predicatepredicate  not(P) is satisfiable if P is not (i.e. is unsatisfiable).  not(P) :- call(P), !, fail.  not(P).  nonsibling(X,Y) :- not( sibling(X,Y) ). IsIs ‘not’‘not’ predicate the same aspredicate the same as ‘logical‘logical negation’negation’? (see p.484)? (see p.484)
  • 42. 42 Evaluation and EpilogEvaluation and Epilog 13.513.5
  • 43. 43ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design TopicsTopics Logic programs areLogic programs are self-documentingself-documenting Pure logic programsPure logic programs separateseparate logic and controllogic and control Prolog fallsProlog falls short ofshort of logic programminglogic programming Implementation techniques areImplementation techniques are improvingimproving Prolog isProlog is a stepa step towardtoward nonproceduralnonprocedural programmingprogramming
  • 44. 44ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Self-documentationSelf-documentation Programming in a higher-level, …Programming in a higher-level, … Application orientation and…Application orientation and… TransparencyTransparency  programs are described in terms of predicates and individuals of the problem domain. Promotes clear, rapid, accurate programmingPromotes clear, rapid, accurate programming
  • 45. 45ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Separation of Logic and ControlSeparation of Logic and Control Simplifies programmingSimplifies programming Correctness only deals with logicCorrectness only deals with logic Optimization in control cannot affectOptimization in control cannot affect correctnesscorrectness ObeysObeys Orthogonality PrincipleOrthogonality Principle
  • 46. 46ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Prolog vs. Logic ProgrammingProlog vs. Logic Programming Definite control strategyDefinite control strategy  Programmers make explicit use of it and the result have little to do with logic  Reasoning about the order of events in Prolog is comparable in difficaulty with most imperative of conventional programming languages CutCut doesn’t make any sense in logic!doesn’t make any sense in logic! notnot doesn’t correspond to logical negationdoesn’t correspond to logical negation
  • 47. 47ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Improving EfficiencyImproving Efficiency Prolog is far from an efficient language.Prolog is far from an efficient language. So, it’s applications are limited to apps inSo, it’s applications are limited to apps in which:which:  Performance is not important  Difficult to implement in a conventional lang. New methods are inventedNew methods are invented Some compilers produce code comparable toSome compilers produce code comparable to LISPLISP
  • 48. 48ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Toward Nonprocedural ProgrammingToward Nonprocedural Programming PurePure logic programs prove the possibility oflogic programs prove the possibility of nonprocedural programming.nonprocedural programming. InIn PrologProlog, DFS requires programmers to think in, DFS requires programmers to think in terms ofterms of operationsoperations and their properand their proper orderingordering in timein time (procedurally).(procedurally). AndAnd Prolog’s control regime is moreProlog’s control regime is more unnaturalunnatural thanthan conventional languages.conventional languages. So,So, there is still much more important work to bethere is still much more important work to be done before nonprocedural programming becomesdone before nonprocedural programming becomes practicalpractical..
  • 49. 49ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Covered Sections of MacLennanCovered Sections of MacLennan 13.113.1 13.213.2 13.313.3 13.413.4  except topics starting on pp. 471, 475, 477, 484, 485, 486, 488 13.513.5
  • 50. 50ECE Dep. of Tehran Univ. - Programming Language DesignECE Dep. of Tehran Univ. - Programming Language Design Presentation ReferencesPresentation References Colmerauer, Alain, Philippe Roussel,Colmerauer, Alain, Philippe Roussel, The Birth of Prolog,The Birth of Prolog, Nov. 1992,Nov. 1992, URL:URL: http://www.lim.univ-http://www.lim.univ- mrs.fr/~colmer/ArchivesPublications/HistoireProlog/19november92.pdfmrs.fr/~colmer/ArchivesPublications/HistoireProlog/19november92.pdf Fisher, J.R., Prolog TutorialFisher, J.R., Prolog Tutorial, 2004, URL:, 2004, URL: http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/contents.htmlhttp://www.csupomona.edu/~jrfisher/www/prolog_tutorial/contents.html MacLennan, Bruce J., Principles of Programming Languages: Design,MacLennan, Bruce J., Principles of Programming Languages: Design, Evaluation and Implementation,Evaluation and Implementation, 3rd ed, Oxford University Press, 19993rd ed, Oxford University Press, 1999 Merritt, Dennis, “Prolog Under the Hood: An Honest Look”Merritt, Dennis, “Prolog Under the Hood: An Honest Look”,, PC AIPC AI magazine, Sep/Oct 1992magazine, Sep/Oct 1992 ““Unification”Unification”, Wikipedia, the free encyclopedia, 25 Sep. 2005, URL:, Wikipedia, the free encyclopedia, 25 Sep. 2005, URL: http://en.wikipedia.org/wiki/Unificationhttp://en.wikipedia.org/wiki/Unification
  • 51. 51 Thank You!Thank You! This lecture was a student lecture presented at theThis lecture was a student lecture presented at the Electrical and Computer Engineering Department ofElectrical and Computer Engineering Department of the University of Tehran, in Fall 2005.the University of Tehran, in Fall 2005. Instructor: Dr. M. SirjaniInstructor: Dr. M. Sirjani