0% found this document useful (0 votes)
14 views116 pages

Lecture1 LP

Uploaded by

Gezae Gebredingl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views116 pages

Lecture1 LP

Uploaded by

Gezae Gebredingl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

Logic Programming

An Introduction to Prolog

September 27, 2018


Contents of this lecture

Part 1: An introduction in the logic programming language


Prolog. Based largely
on [Clocksin and Mellish, 2003].
Contents of this lecture

Part 1: An introduction in the logic programming language


Prolog. Based largely
on [Clocksin and Mellish, 2003].
Part 2: A review of the theoretical basis of logic
programming. Based on corresponding topics in
[Ben-Ari, 2001] and [Nilsson and Maluszynski, 2000].
Contents of this lecture

Part 1: An introduction in the logic programming language


Prolog. Based largely
on [Clocksin and Mellish, 2003].
Part 2: A review of the theoretical basis of logic
programming. Based on corresponding topics in
[Ben-Ari, 2001] and [Nilsson and Maluszynski, 2000].
Part 3: Advanced topics in logic programming/Prolog. Based
on corresponding topics in [Ben-Ari, 2001] and
[Nilsson and Maluszynski, 2000].
Organizatorial items

I Lecturer: Isabela Drămnesc


I Course webpage:
http://staff.fmi.uvt.ro/~isabela.dramnesc
I 14 Courses
I 7 Labs: working with Prolog
I Handouts: will be posted on the webpage of the lecture
I Grading:
I 50% : 25% (weekly seminar assignments + activity +
homework), 25% (the practical exam during the last lab)
I 50% : 1 written exam (colloquy) at the end of the semester
(during the last lecture)
Recalling the Von Neumann machine
I The von Neumann machine (architecture) is characterized by:
I large uniform store of memory,
I processing unit with registers.
I A program for the von Neumann machine: a sequence of
instructions for
I moving data between memory and registers,
I carrying out arithmetical-logical operations between registers,
I control, etc.
I Most programming languages (like C, C++, Java, etc.) are
influenced by and were designed for the von Neumann
architecture.
I In fact, such programming languages take into account the
architecture of the machine they address and can be used to
write efficient programs.
I The above point is by no means trivial, and it leads to a
separation of work (“the software crisis”):
I finding solutions of problems (using reasoning),
I implementation of the solutions (mundane and tedious).
Alternatives to the von Neumann approach

I How about making programming part of problem solving?


I i.e. write programs as you solve problems?
I “rapid prototyping”?
I Logic programming is derived from an abstract model (not a
reorganization/abstraction of a von Neumann machine).
I In logic programming
I program = set of axioms,
I computation = constructive proof of a goal statement.
Logic programming: some history

I David Hilbert’s program (early 20th century): formalize all


mathematics using a finite, complete, consistent set of axioms.
I Kurt Gödel’s incompleteness theorem (1931): any theory
containing arithmetic cannot prove its own consistency.
I Alonzo Church and Alan Turing (independently, 1936):
undecidability - no mechanical method to decide truth (in
general).
Logic programming: some history

I Alan Robinson (1965): the resolution method for first order


logic (i.e. machine reasoning in first order logic).
I Robert Kowalski (1971): procedural interpretation of Horn
clauses, i.e. computation in logic.
I Alan Colmerauer (1972): Prolog (PROgrammation en
LOGique).prover.
I David H.D. Warren (mid-late 1970’s): efficient
implementation of Prolog.
I 1981 Japanese Fifth Generation Computer project: project to
build the next generation computers with advanced AI
capabilities (using a concurrent Prolog as the programming
language).
Applications of logic programming

I Symbolic computation:
I relational databases,
I mathematical logic,
I abstract problem solving,
I natural language understanding,
I symbolic equation solving,
I design automation,
I artificial intelligence,
I biochemical structure analysis, etc.
Applications of logic programming (cont’d)

I Industrial applications:
I aviation:
I SCORE - a longterm aiport capacity management system for
coordinated airports (20% of air traffic worldwide, according
to www.pdc-aviation.com)
I FleetWatch - operational control, used by 21 international air
companies.
I personnel planning: StaffPlan (airports in Barcelona, Madrid;
Hovedstaden region in Denmark).
I information management for disasters: ARGOS - crisis
management in CBRN (chemical, biological, radiological and
nuclear) incidents – used by Australia, Brasil, Canada, Ireland,
Denmark, Sweden, Norway, Poland, Estonia, Lithuania and
Montenegro.
Problem solving with Prolog

I Programming in Prolog:
I rather than prescribe a sequence of steps to solve a problem,
I describe known facts and relations, then ask questions.
I Use Prolog to solve problems that involve objects and
relations between objects.
I Examples:
I Objects: “John”, “book”, “jewel”, etc.
I Relations: “John owns the book”, “The jewel is valuable”.
I Rules: “Two people are sisters if they are both females and
they have the same parents”.
Problem solving with Prolog (cont’d)

I Attention!!! Problem solving requires modelling of the


problem (with its respective limitations).
I Problem solving with Prolog:
I declare facts about objects and their relations,
I define rules about objects and their relations,
I ask questions about objects and their relations.
I Programming in Prolog: a conversation with the Prolog
interpreter.
Facts
I Stating a fact in Prolog:
l i k e s ( j o h n n y , mary ) .
Facts
I Stating a fact in Prolog:
l i k e s ( j o h n n y , mary ) .
I Names of relations (predicates) and objects are written in
lower case letter.
Facts
I Stating a fact in Prolog:
l i k e s ( j o h n n y , mary ) .
I Names of relations (predicates) and objects are written in
lower case letter.
I Prolog uses (mostly) prefix notation (but there are exceptions).
Facts
I Stating a fact in Prolog:
l i k e s ( j o h n n y , mary ) .
I Names of relations (predicates) and objects are written in
lower case letter.
I Prolog uses (mostly) prefix notation (but there are exceptions).
I Facts end with “.” (full stop).
Facts
I Stating a fact in Prolog:
l i k e s ( j o h n n y , mary ) .
I Names of relations (predicates) and objects are written in
lower case letter.
I Prolog uses (mostly) prefix notation (but there are exceptions).
I Facts end with “.” (full stop).

I A model is built in Prolog, and facts describe the model.


Facts
I Stating a fact in Prolog:
l i k e s ( j o h n n y , mary ) .
I Names of relations (predicates) and objects are written in
lower case letter.
I Prolog uses (mostly) prefix notation (but there are exceptions).
I Facts end with “.” (full stop).

I A model is built in Prolog, and facts describe the model.


I The user has to be aware of the interpretation:
l i k e s ( j o h n , mary ) .
l i k e s ( mary , j o h n ) .
are not the same thing (unless explicitly specified).
Facts
I Stating a fact in Prolog:
l i k e s ( j o h n n y , mary ) .
I Names of relations (predicates) and objects are written in
lower case letter.
I Prolog uses (mostly) prefix notation (but there are exceptions).
I Facts end with “.” (full stop).

I A model is built in Prolog, and facts describe the model.


I The user has to be aware of the interpretation:
l i k e s ( j o h n , mary ) .
l i k e s ( mary , j o h n ) .
are not the same thing (unless explicitly specified).
I Arbitrary numbers of arguments are allowed.
Facts
I Stating a fact in Prolog:
l i k e s ( j o h n n y , mary ) .
I Names of relations (predicates) and objects are written in
lower case letter.
I Prolog uses (mostly) prefix notation (but there are exceptions).
I Facts end with “.” (full stop).

I A model is built in Prolog, and facts describe the model.


I The user has to be aware of the interpretation:
l i k e s ( j o h n , mary ) .
l i k e s ( mary , j o h n ) .
are not the same thing (unless explicitly specified).
I Arbitrary numbers of arguments are allowed.
I Notation: likes /2 indicates a binary predicate.
Facts
I Stating a fact in Prolog:
l i k e s ( j o h n n y , mary ) .
I Names of relations (predicates) and objects are written in
lower case letter.
I Prolog uses (mostly) prefix notation (but there are exceptions).
I Facts end with “.” (full stop).

I A model is built in Prolog, and facts describe the model.


I The user has to be aware of the interpretation:
l i k e s ( j o h n , mary ) .
l i k e s ( mary , j o h n ) .
are not the same thing (unless explicitly specified).
I Arbitrary numbers of arguments are allowed.
I Notation: likes /2 indicates a binary predicate.
I Facts are part of the Prolog database (knowledge base).
Queries

I A query in Prolog:
?− owns ( mary , book ) .
Prolog searches in the knowledge base for facts that match
the question:
Queries

I A query in Prolog:
?− owns ( mary , book ) .
Prolog searches in the knowledge base for facts that match
the question:
I Prolog answers true if :
Queries

I A query in Prolog:
?− owns ( mary , book ) .
Prolog searches in the knowledge base for facts that match
the question:
I Prolog answers true if :
I the predicates are the same,
Queries

I A query in Prolog:
?− owns ( mary , book ) .
Prolog searches in the knowledge base for facts that match
the question:
I Prolog answers true if :
I the predicates are the same,
I arguments are the same,
Queries

I A query in Prolog:
?− owns ( mary , book ) .
Prolog searches in the knowledge base for facts that match
the question:
I Prolog answers true if :
I the predicates are the same,
I arguments are the same,
I Ortherwise the answer is false :
Queries

I A query in Prolog:
?− owns ( mary , book ) .
Prolog searches in the knowledge base for facts that match
the question:
I Prolog answers true if :
I the predicates are the same,
I arguments are the same,
I Ortherwise the answer is false :
I only what is known is true (“closed world assumption”),
Queries

I A query in Prolog:
?− owns ( mary , book ) .
Prolog searches in the knowledge base for facts that match
the question:
I Prolog answers true if :
I the predicates are the same,
I arguments are the same,
I Ortherwise the answer is false :
I only what is known is true (“closed world assumption”),
I Attention: false may not mean that the answer is false (but
more like “not derivable from the knowledge”).
Variables
I Think variables in predicate logic.
Variables
I Think variables in predicate logic.
I Instead of:
?− l i k e s ( j o h n , mary ) .
?− l i k e s ( j o h n , a p p l e s ) .
?− l i k e s ( j o h n , candy ) .
ask something like “What does John like?” (i.e. give
everything that John likes).
Variables
I Think variables in predicate logic.
I Instead of:
?− l i k e s ( j o h n , mary ) .
?− l i k e s ( j o h n , a p p l e s ) .
?− l i k e s ( j o h n , candy ) .
ask something like “What does John like?” (i.e. give
everything that John likes).
I Variables stand for objects to be determined by Prolog.
Variables
I Think variables in predicate logic.
I Instead of:
?− l i k e s ( j o h n , mary ) .
?− l i k e s ( j o h n , a p p l e s ) .
?− l i k e s ( j o h n , candy ) .
ask something like “What does John like?” (i.e. give
everything that John likes).
I Variables stand for objects to be determined by Prolog.
I Variables can be:
Variables
I Think variables in predicate logic.
I Instead of:
?− l i k e s ( j o h n , mary ) .
?− l i k e s ( j o h n , a p p l e s ) .
?− l i k e s ( j o h n , candy ) .
ask something like “What does John like?” (i.e. give
everything that John likes).
I Variables stand for objects to be determined by Prolog.
I Variables can be:
I instantiated - there is an object the variable stands for,
Variables
I Think variables in predicate logic.
I Instead of:
?− l i k e s ( j o h n , mary ) .
?− l i k e s ( j o h n , a p p l e s ) .
?− l i k e s ( j o h n , candy ) .
ask something like “What does John like?” (i.e. give
everything that John likes).
I Variables stand for objects to be determined by Prolog.
I Variables can be:
I instantiated - there is an object the variable stands for,
I uninstantiated - it is not (yet) known what the variable stands
for.
Variables
I Think variables in predicate logic.
I Instead of:
?− l i k e s ( j o h n , mary ) .
?− l i k e s ( j o h n , a p p l e s ) .
?− l i k e s ( j o h n , candy ) .
ask something like “What does John like?” (i.e. give
everything that John likes).
I Variables stand for objects to be determined by Prolog.
I Variables can be:
I instantiated - there is an object the variable stands for,
I uninstantiated - it is not (yet) known what the variable stands
for.
I In Prolog variables start with CAPITAL LETTERS:
?− l i k e s ( j o h n , X ) .
Prolog computation: example

I Consider the following facts in a Prolog knowledge base:


...
l i k e s ( john , f l o w e r s ) .
l i k e s ( j o h n , mary ) .
l i k e s ( p a u l , mary ) .
...
Prolog computation: example

I Consider the following facts in a Prolog knowledge base:


...
l i k e s ( john , f l o w e r s ) .
l i k e s ( j o h n , mary ) .
l i k e s ( p a u l , mary ) .
...
I To the query
?− l i k e s ( j o h n , X ) .
Prolog will answer
X = flowers
and wait for further instructions.
Prolog answer computation

I Prolog searches the knowledge base for a fact that matches


the query,
Prolog answer computation

I Prolog searches the knowledge base for a fact that matches


the query,
I when a match is found, it is marked.
Prolog answer computation

I Prolog searches the knowledge base for a fact that matches


the query,
I when a match is found, it is marked.
I if the user presses “Enter”, the search is over,
Prolog answer computation

I Prolog searches the knowledge base for a fact that matches


the query,
I when a match is found, it is marked.
I if the user presses “Enter”, the search is over,
I if the user presses “;” then “Enter”, Prolog looks for a new
match, from the previously marked place, and with the
variable(s) in the query uninstantiated.
Prolog answer computation

I Prolog searches the knowledge base for a fact that matches


the query,
I when a match is found, it is marked.
I if the user presses “Enter”, the search is over,
I if the user presses “;” then “Enter”, Prolog looks for a new
match, from the previously marked place, and with the
variable(s) in the query uninstantiated.
I In the example above, two more “; Enter” will determine
Prolog to answer:
X = mary .
false
Prolog answer computation

I Prolog searches the knowledge base for a fact that matches


the query,
I when a match is found, it is marked.
I if the user presses “Enter”, the search is over,
I if the user presses “;” then “Enter”, Prolog looks for a new
match, from the previously marked place, and with the
variable(s) in the query uninstantiated.
I In the example above, two more “; Enter” will determine
Prolog to answer:
X = mary .
false
I When no (more) matching facts are found in the knowledge
base, Prolog answers false .
Conjunctions: more complex queries

I Consider the following facts:


likes ( mary , food ) .
likes ( mary , wine ) .
likes ( john , wine ) .
likes ( john , mary ) .
Conjunctions: more complex queries

I Consider the following facts:


likes ( mary , food ) .
likes ( mary , wine ) .
likes ( john , wine ) .
likes ( john , mary ) .
I And the query:
?− l i k e s ( j o h n , mary ) , l i k e s ( mary , j o h n ) .
Conjunctions: more complex queries

I Consider the following facts:


likes ( mary , food ) .
likes ( mary , wine ) .
likes ( john , wine ) .
likes ( john , mary ) .
I And the query:
?− l i k e s ( j o h n , mary ) , l i k e s ( mary , j o h n ) .
I the query reads “does john like mary and does mary like john?”
Conjunctions: more complex queries

I Consider the following facts:


likes ( mary , food ) .
likes ( mary , wine ) .
likes ( john , wine ) .
likes ( john , mary ) .
I And the query:
?− l i k e s ( j o h n , mary ) , l i k e s ( mary , j o h n ) .
I the query reads “does john like mary and does mary like john?”
I Prolog will answer false : it searches for each goal in turn (all
goals have to be satisfied, if not, it will fail, i.e. answer false ).
Conjunctions: more complex queries

I For the query:


?− l i k e s ( mary , X ) , l i k e s ( j o h n , X ) .
Conjunctions: more complex queries

I For the query:


?− l i k e s ( mary , X ) , l i k e s ( j o h n , X ) .
I Prolog: try to satisfy the first goal (if it is satisfied put a
placemarker), then try to satisfy the second goal (if yes, put a
placemarker).
Conjunctions: more complex queries

I For the query:


?− l i k e s ( mary , X ) , l i k e s ( j o h n , X ) .
I Prolog: try to satisfy the first goal (if it is satisfied put a
placemarker), then try to satisfy the second goal (if yes, put a
placemarker).
I If at any point there is a failure, backtrack to the last
placemarker and try alternatives.
Example: conjunction, backtracking
The way Prolog computes the answer to the above query is
represented:
I In Figure 1, the first goal is satisfied, Prolog attempts to find
a match for the second goal (with the variable instantiated).
I The failure to find a match in the knowledge base causes
backtracking, see Figure 2.
I The new alternative tried is successful for both goals, see
Figure 3.

Figure: Success for the first goal.


Figure: Second goal failure causes backtracking.
Figure: Success with alternative instantiation.
Rules

I “John likes all people” can be represented as:


Rules

I “John likes all people” can be represented as:


likes ( john , alfred ).
likes ( john , bertrand ).
likes ( john , charles ).
likes ( john , david ) .
...
but this is tedious!!!
Rules

I “John likes all people” can be represented as:


likes ( john , alfred ).
likes ( john , bertrand ).
likes ( john , charles ).
likes ( john , david ) .
...
but this is tedious!!!
l i k e s ( john , X ) .
but this should be only for people!!!
Rules

I “John likes all people” can be represented as:


likes ( john , alfred ).
likes ( john , bertrand ).
likes ( john , charles ).
likes ( john , david ) .
...
but this is tedious!!!
l i k e s ( john , X ) .
but this should be only for people!!!
I Enter rules: “John likes any object, but only that which is a
person” is a rule about what (who) John likes.
Rules

I “John likes all people” can be represented as:


likes ( john , alfred ).
likes ( john , bertrand ).
likes ( john , charles ).
likes ( john , david ) .
...
but this is tedious!!!
l i k e s ( john , X ) .
but this should be only for people!!!
I Enter rules: “John likes any object, but only that which is a
person” is a rule about what (who) John likes.
I Rules express that a fact depends on other facts.
Rules as definitions
I Rules can be used to express “definitions”.
Rules as definitions
I Rules can be used to express “definitions”.
I Example:
Rules as definitions
I Rules can be used to express “definitions”.
I Example:
“X is a bird if X is an animal and X has feathers.”
Rules as definitions
I Rules can be used to express “definitions”.
I Example:
“X is a bird if X is an animal and X has feathers.”
I Example:
Rules as definitions
I Rules can be used to express “definitions”.
I Example:
“X is a bird if X is an animal and X has feathers.”
I Example:
“X is a sister of Y if X is female and X and Y have the same
parents.”
Rules as definitions
I Rules can be used to express “definitions”.
I Example:
“X is a bird if X is an animal and X has feathers.”
I Example:
“X is a sister of Y if X is female and X and Y have the same
parents.”
I Attention! The above notion of “definition” is not the same
as the notion of definition in logic:
Rules as definitions
I Rules can be used to express “definitions”.
I Example:
“X is a bird if X is an animal and X has feathers.”
I Example:
“X is a sister of Y if X is female and X and Y have the same
parents.”
I Attention! The above notion of “definition” is not the same
as the notion of definition in logic:
I such definitions allow detection of the predicates in the head of
the rule,
Rules as definitions
I Rules can be used to express “definitions”.
I Example:
“X is a bird if X is an animal and X has feathers.”
I Example:
“X is a sister of Y if X is female and X and Y have the same
parents.”
I Attention! The above notion of “definition” is not the same
as the notion of definition in logic:
I such definitions allow detection of the predicates in the head of
the rule,
I but there may be other ways (i.e. other rules with the same
head) to detect such predicates,
Rules as definitions
I Rules can be used to express “definitions”.
I Example:
“X is a bird if X is an animal and X has feathers.”
I Example:
“X is a sister of Y if X is female and X and Y have the same
parents.”
I Attention! The above notion of “definition” is not the same
as the notion of definition in logic:
I such definitions allow detection of the predicates in the head of
the rule,
I but there may be other ways (i.e. other rules with the same
head) to detect such predicates,
I in order to have full definitions “iff” is needed instead of “if”.
Rules as definitions
I Rules can be used to express “definitions”.
I Example:
“X is a bird if X is an animal and X has feathers.”
I Example:
“X is a sister of Y if X is female and X and Y have the same
parents.”
I Attention! The above notion of “definition” is not the same
as the notion of definition in logic:
I such definitions allow detection of the predicates in the head of
the rule,
I but there may be other ways (i.e. other rules with the same
head) to detect such predicates,
I in order to have full definitions “iff” is needed instead of “if”.
I Rules are general statements about objects and their
relationships (in general variables occur in rules, but not
always).
Rules in Prolog

I Rules in Prolog have a head and a body.


Rules in Prolog

I Rules in Prolog have a head and a body.


I The body of the rule describes the goals that have to be
satisfied for the head to be true.
Rules in Prolog

I Rules in Prolog have a head and a body.


I The body of the rule describes the goals that have to be
satisfied for the head to be true.
I Example:
l i k e s ( j o h n , X) :−
l i k e s (X , w i n e ) .
l i k e s ( j o h n , X) :−
l i k e s (X , w i n e ) , l i k e s (X , f o o d ) .
l i k e s ( j o h n , X) :−
f e m a l e (X ) , l i k e s (X , w i n e ) .
Rules in Prolog

I Rules in Prolog have a head and a body.


I The body of the rule describes the goals that have to be
satisfied for the head to be true.
I Example:
l i k e s ( j o h n , X) :−
l i k e s (X , w i n e ) .
l i k e s ( j o h n , X) :−
l i k e s (X , w i n e ) , l i k e s (X , f o o d ) .
l i k e s ( j o h n , X) :−
f e m a l e (X ) , l i k e s (X , w i n e ) .
I Attention! The scope of the variables that occur in a rule is
the rule itself (rules do not share variables).
Example (royals)
I Knowledge base:
male ( a l b e r t ) .
male ( edward ) .
female ( a l i c e ) .
female ( v i c t o r i a ) .
parents ( alice , albert , victoria ).
p a r e n t s ( edward , a l b e r t , victoria ).
s i s t e r o f (X , Y): −
f e m a l e (X ) ,
p a r e n t s (X , M, F ) .
p a r e n t s (Y , M, F ) .
Example (royals)
I Knowledge base:
male ( a l b e r t ) .
male ( edward ) .
female ( a l i c e ) .
female ( v i c t o r i a ) .
parents ( alice , albert , victoria ).
p a r e n t s ( edward , a l b e r t , victoria ).
s i s t e r o f (X , Y): −
f e m a l e (X ) ,
p a r e n t s (X , M, F ) .
p a r e n t s (Y , M, F ) .
I Goals:
?− s i s t e r o f ( a l i c e , edward ) .
?− s i s t e r o f ( a l i c e , X ) .
Exercise (thieves)

I Consider the following:

/∗1∗/ t h i e f ( j o h n ) .

/∗2∗/ l i k e s ( mary , f o o d ) .
/∗3∗/ l i k e s ( mary , w i n e ) .
/∗4∗/ l i k e s ( j o h n , X): − l i k e s (X , w i n e ) .

/∗5∗/ m a y s t e a l (X , Y) :−
t h i e f (X ) , l i k e s (X , Y ) .
I Explain how the query
?− m a y s t e a l ( j o h n , X ) .
is executed by Prolog.
I Prolog programs are built from terms (written as strings of
characters).
I The following are terms:
I constants,
I variables,
I structures.
Constants

I Constants are simple (basic) terms.


Constants

I Constants are simple (basic) terms.


I They name specific things or predicates (no functions in
Prolog).
Constants

I Constants are simple (basic) terms.


I They name specific things or predicates (no functions in
Prolog).
I Constants are of 2 types:
Constants

I Constants are simple (basic) terms.


I They name specific things or predicates (no functions in
Prolog).
I Constants are of 2 types:
I atoms,
Constants

I Constants are simple (basic) terms.


I They name specific things or predicates (no functions in
Prolog).
I Constants are of 2 types:
I atoms,
I numbers: integers, rationals (with special libraries), reals
(floating point representation).
Examples of atoms

I atoms:
I likes ,
I a (lowercase letters),
I =,
I −−>,
I ’Void’ (anything between single quotes),
I george smith (constants may contain underscore),
I not atoms:
I 314a5 (cannot start with a number),
I george−smith (cannot contain a hyphen),
I George (cannot start with a capital letter),
I something (cannot start with underscore).
Variables

I Variables are simple (basic) terms,


I written in uppercase or starting with underscore ,
I Examples: X, Input, something, (the last one called
anonymous variable).
I Anonymous variables need not have consistent interpretations
(they need not be bound to the same value):
?− l i k e s ( , j o h n ) . % d o e s anybody l i k e John ?
?− l i k e s ( , ) . % d o e s anybody l i k e anybody ?
Structures

I Structure are compound terms, single objects consisting of


collections of objects (terms),
I they are used to organize the data.
I A structure is specified by its functor (name) and its
components
owns ( john , book ( w u t h e r i n g h e i g h t s , b r o n t e ) ) .
book ( w u t h e r i n g h e i g h t s , a u t h o r ( e m i l y , b r o n t e ) ) .

?−owns ( john , book (X , a u t h o r (Y , b r o n t e ) ) ) .


% d o e s John own a book (X) by B r o n t e (Y , b r o n t e ) ?
Characters in Prolog

I Characters:
I A-Z
I a-z
I 0-9
I +-*/\ ˜ˆ<>: .
I ? @#$&
I Characters are ASCII (printing) characters with codes greater
than 32.
I Remark: ’ ’ allows the use of any character.
Arithmetic operators

I Arithmetic operators:
I +,
I −,
I ∗,
I /,
I +(x, ∗(y , z)) is equivalent with x + (y · z)
I Operators do not cause evaluation in Prolog.
I Example: 3+4 (structure) does not have the same meaning
with 7 (term).
I X is 3+4 causes evaluation ( is represents the evaluator in
Prolog).
I The result of the evaluation is that X is assigned the value 7.
Parsing arithmetic expressions

I To parse an arithmetic expression you need to know:


I The position:
I infix: x + y , x ∗ y
I prefix −x
I postfix x!
I Precedence: x + y ∗ z ?
I Associativity: What is x + y + z? x + (y + z) or (x + y ) + z?
I Each operator has a precedence class:
I 1 - highest
I 2 - lower
I ...
I lowest
I ∗ / have higher precedence than + −
I 8/2/2 evaluates to:
I 8 (8/(2/2)) - right associative?
I or 2 ((8/2)/2) - left associative?
I Arithmetic operators are left associative.
The unification predicate ’=’

I = - infix built-in predicate.


?−X = Y .
Prolog will try to match(unify) X and Y, and will answer true
if successful.
The unification predicate ’=’

I = - infix built-in predicate.


?−X = Y .
Prolog will try to match(unify) X and Y, and will answer true
if successful.
I In general, we try to unify 2 terms (which can be any of
constants, variables, structures):
?−T1 = T2 .
The unification predicate ’=’

I = - infix built-in predicate.


?−X = Y .
Prolog will try to match(unify) X and Y, and will answer true
if successful.
I In general, we try to unify 2 terms (which can be any of
constants, variables, structures):
?−T1 = T2 .
I Remark on terminology: while in some Prolog sources the
term “matching” is used, note that in the (logic) literature
matching is used for the situation where one of the terms is
ground (i.e. contains no variables). What = does is
unification.
The unification procedure
Summary of the unification procedure ?− T1 = T2:
I If T1 and T2 are identical constants, success (Prolog answers
true);
The unification procedure
Summary of the unification procedure ?− T1 = T2:
I If T1 and T2 are identical constants, success (Prolog answers
true);
I If T1 and T2 are uninstantiated variable, success (variable
renaming);
The unification procedure
Summary of the unification procedure ?− T1 = T2:
I If T1 and T2 are identical constants, success (Prolog answers
true);
I If T1 and T2 are uninstantiated variable, success (variable
renaming);
I If T1 is an uninstantiated variable and T2 is a constant or a
structure, success, and T1 is instantiated with T2;
The unification procedure
Summary of the unification procedure ?− T1 = T2:
I If T1 and T2 are identical constants, success (Prolog answers
true);
I If T1 and T2 are uninstantiated variable, success (variable
renaming);
I If T1 is an uninstantiated variable and T2 is a constant or a
structure, success, and T1 is instantiated with T2;
I If T1 and T2 are instantiated variables, then decide according
to their value (they unify - if they have the same value,
otherwise not);
The unification procedure
Summary of the unification procedure ?− T1 = T2:
I If T1 and T2 are identical constants, success (Prolog answers
true);
I If T1 and T2 are uninstantiated variable, success (variable
renaming);
I If T1 is an uninstantiated variable and T2 is a constant or a
structure, success, and T1 is instantiated with T2;
I If T1 and T2 are instantiated variables, then decide according
to their value (they unify - if they have the same value,
otherwise not);
I If T1 is a structure: f (X1 , X2 , ..., Xn ) and T2 has the same
functor (name): f (Y1 , Y2 , ..., Yn ) and the same number of
arguments, then unify these arguments recursively (X1 = Y1 ,
X2 = Y2 , etc.). If all the arguments unify, then the answer is
true, otherwise the answer is false (unification fails);
The unification procedure
Summary of the unification procedure ?− T1 = T2:
I If T1 and T2 are identical constants, success (Prolog answers
true);
I If T1 and T2 are uninstantiated variable, success (variable
renaming);
I If T1 is an uninstantiated variable and T2 is a constant or a
structure, success, and T1 is instantiated with T2;
I If T1 and T2 are instantiated variables, then decide according
to their value (they unify - if they have the same value,
otherwise not);
I If T1 is a structure: f (X1 , X2 , ..., Xn ) and T2 has the same
functor (name): f (Y1 , Y2 , ..., Yn ) and the same number of
arguments, then unify these arguments recursively (X1 = Y1 ,
X2 = Y2 , etc.). If all the arguments unify, then the answer is
true, otherwise the answer is false (unification fails);
I In any other case, unification fails.
Occurs check

I Consider the following unification problem:


?− X = f (X ) .
Occurs check

I Consider the following unification problem:


?− X = f (X ) .
I Answer of Prolog:
X = f (∗∗).
Occurs check

I Consider the following unification problem:


?− X = f (X ) .
I Answer of Prolog:
X = f (∗∗).

X = f (X ) .
Occurs check

I Consider the following unification problem:


?− X = f (X ) .
I Answer of Prolog:
X = f (∗∗).

X = f (X ) .

I In fact this is due to the fact that according to the unification


procedure, the result is
X = f(X) = f(f(X)) = ...= f ( f (...( f (X )...))) - an infinite
loop would be generated.
I Unification should fail in such situations.
I Unification should fail in such situations.
I To avoid them, perform an occurs check: If T1 is a variable
and T2 a structure, in an expression like T1 = T2 make sure
that T1 does not occur in T2.
I Unification should fail in such situations.
I To avoid them, perform an occurs check: If T1 is a variable
and T2 a structure, in an expression like T1 = T2 make sure
that T1 does not occur in T2.
I Occurence check is deactivated by default in most Prolog
implementations (is computationally very expensive) - Prolog
trades correctness for speed.
I Unification should fail in such situations.
I To avoid them, perform an occurs check: If T1 is a variable
and T2 a structure, in an expression like T1 = T2 make sure
that T1 does not occur in T2.
I Occurence check is deactivated by default in most Prolog
implementations (is computationally very expensive) - Prolog
trades correctness for speed.
I A predicate complementary to unification:
I Unification should fail in such situations.
I To avoid them, perform an occurs check: If T1 is a variable
and T2 a structure, in an expression like T1 = T2 make sure
that T1 does not occur in T2.
I Occurence check is deactivated by default in most Prolog
implementations (is computationally very expensive) - Prolog
trades correctness for speed.
I A predicate complementary to unification:
I \= succeeds only when = fails,
I Unification should fail in such situations.
I To avoid them, perform an occurs check: If T1 is a variable
and T2 a structure, in an expression like T1 = T2 make sure
that T1 does not occur in T2.
I Occurence check is deactivated by default in most Prolog
implementations (is computationally very expensive) - Prolog
trades correctness for speed.
I A predicate complementary to unification:
I \= succeeds only when = fails,
I i.e. T1 \= T2 cannot be unified.
Built-in predicates for arithmetic

I Prolog has built-in numbers.


I Built-in predicates on numbers include:
X = Y,
X \= Y,
X < Y,
X > Y,
X =< Y,
X >= Y,
with the expected behaviour.
I Note that variables have to be instantiated in most cases
(with the exception of the first two above, where unification is
performed in the case of uninstantiation).
The arithmetic evaluator is

I Prolog also provides arithmetic operators (functions), e.g.:


+, −, ∗, /, mod, rem, abs, max, min, random, floor , ceiling
etc, but these cannot be used directly for computation(2+3
means 2+3, not 5) - expressions involving operators are not
evaluated by default.
The arithmetic evaluator is

I Prolog also provides arithmetic operators (functions), e.g.:


+, −, ∗, /, mod, rem, abs, max, min, random, floor , ceiling
etc, but these cannot be used directly for computation(2+3
means 2+3, not 5) - expressions involving operators are not
evaluated by default.
I The Prolog evaluator is has the form:
X i s Expr .
where X is an uninstantiated variable, and Expr is an
arithmetic expression, where all variables must be instantiated
(Prolog has no equation solver).
Example (with arithmetic(1))
r e i g n s ( r h o n d r i , 844 , 8 7 8 ) .
r e i g n s ( anarawd , 8 7 8 , 9 1 6 ) .
r e i g n s ( hywel dda , 916 , 9 5 0 ) .
r e i g n s ( l a g o a p i d w a l , 950 , 9 7 9 ) .
r e i g n s ( h y w e l a p i e u a f , 979 , 9 8 5 ) .
r e i g n s ( cadwallon , 985 , 9 8 6 ) .
r e i g n s ( maredudd , 9 8 6 , 9 9 9 ) .
p r i n c e (X , Y): −
r e i g n s (X , A , B ) ,
Y >= A ,
Y =< B .

?− p r i n c e ( c a d w a l l o n , 9 8 6 ) .
true
?− p r i n c e (X , 9 7 9 ) .
X = lago ap idwal ;
X = hywel ap ieuaf
Example (with arithmetic(2))
pop ( p l a c e 1 , 203).
pop ( p l a c e 2 , 548).
pop ( p l a c e 3 , 800).
pop ( p l a c e 4 , 108).

area ( place1 , 3) .
area ( place2 , 1) .
area ( place3 , 4) .
area ( place4 , 3) .
d e n s i t y (X , Y): −
pop (X , P ) ,
a r e a (X , A ) ,
Y i s P/A .

?− d e n s i t y ( p l a c e 3 , X ) .
X = 200
true
I In this lecture the following were discussed:
I asserting facts about objects,
I asking questions about facts,
I using variables, scopes of variables,
I conjunctions,
I an introduction to backtracking (in examples),
I Prolog syntax: terms (constants, variables, structures),
I Arithmetic in Prolog,
I Unification procedure,
I Subtle point: occurs check.
I All things SWIProlog can be found at
http://www.swi-prolog.org.
I Install SWI-Prolog and try out the examples in the lecture.
I Read: Chapter 1 and Chapter 2 (including exercises section)
of [Clocksin and Mellish, 2003].
Ben-Ari, M. (2001).
Mathematical Logic for Computer Science.
Springer Verlag, London, 2nd edition.
Clocksin, W. F. and Mellish, C. S. (2003).
Programming in Prolog.
Springer, Berlin, 5th edition.
Nilsson, U. and Maluszynski, J. (2000).
Logic, Programming and Prolog.
copyright Ulf Nilsson and Jan Maluszynski, 2nd edition.

You might also like