topic 4b an overview of prolog n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Topic 4b - An Overview of Prolog PowerPoint Presentation
Download Presentation
Topic 4b - An Overview of Prolog

Loading in 2 Seconds...

play fullscreen
1 / 142

Topic 4b - An Overview of Prolog - PowerPoint PPT Presentation


  • 205 Views
  • Uploaded on

Topic 4b - An Overview of Prolog. A Successful Automated Reasoning System Prolog is one of the most successful attempts at producing a language for automated reasoning. Predicate Calculus provides the structure for representing knowledge in the language of logic. An Overview of Prolog

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Topic 4b - An Overview of Prolog' - berne


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
topic 4b an overview of prolog
Topic 4b - An Overview of Prolog
  • A Successful Automated Reasoning System
  • Prolog is one of the most successful attempts at producing a language for automated reasoning.
  • Predicate Calculus provides the structure for representing knowledge in the language of logic.
  • An Overview of Prolog
    • designed to give a practical implementation of the language of Predicate Calculus
    • a mechanism for entering a database of knowledge in terms of
      • facts and
      • relationships between these facts (i.e. rules)
    • serves as a database/query system
      • the query becomes the goal or theorems which Prolog tries to prove
  • History
    • 1972, Philippe Rousell and Alan Colmerauer of the ‘Group d’Intelligence Artificielle’ at the University of Marseille
    • First interpreter written in Algol-W in 1972, then in FORTRAN in 1973, then in Pascal in 1976.
prolog references
Prolog References

Prolog Programming for Artificial Intelligence

Ivan Bratko

1986, Addison-Wesley

Luger Chapters 6 , 13

Programming in Prolog

W.F. Clocksin and C.S. Mellish

1987, Springer-Verlag

A Prolog Primer

Jean B. Rogers

1986, Addison-Wesley

The Art of Prolog

Sterling and Shapiro

1986, MIT Press

some features of prolog
Some Features of Prolog
  • resolution theorem-proving (or unification)
  • rewrites and stores database in the form of Horn Clauses (See next slide - Omit at KG)
  • depth-first strategy in searching for a pattern-match
  • is more declarative than procedural
  • Is Prolog a True Logic Programming Language? No!
    • A language must have extra features to those of a purely logical nature:
      • a stack scheduling policy
      • communication predicates (I/O)
      • control features (cut, repeat, ...)
      • dynamic database modification (assert, retract,....)
    • However, Prolog is still very close to a pure logic programming language.
horn clause s omit at kg
Horn Clauses (Omit at KG)
  • Logic programming is commonly done using predicate calculus expressions called "Horn clauses" (named after Alfred Horn, who first studied them).
    • Horn clauses are clauses that satisfy a particular restriction:
      • at most one of the literals in the clause is unnegated.
  • Thus, the following are Horn clauses (assuming that P, Q, Pi, P2,..., Pk represent propositions each consisting of a predicate and the required number of terms):

not PÚQ

not P1Ú not P2Ú... Ú not Pk V Q

not P1Ú not P2Ú... Ú not Pk

P

  • These can be rewritten:

P => QP1Ù P2 Ù... Ù Pk => Q

P1Ù P2 Ù... Ù Pk => F

P

    • The third of these expressions employs F to indicate falseness or the null clause.
horn clause s contd omit at kg
Horn Clauses - Contd.(Omit at KG)
  • These are often written in a "goal-oriented" format in which the implied literal (the goal) is on the left and ',' is used for the AND operator:

Q <= P

Q <= P1, P2, …, Pk

<= P1, P2, …, Pk

P <=

    • The third and fourth examples above show cases in which the goal arrow has nothing to its left (in the former case) and nothing to its right (in the latter case).
    • The null clause is a Horn clause, and can be written <=
  • Horn clauses in the goal-oriented format are used to program in Prolog.
useful in solving the problem of non monotonic reasoning
Useful in Solving the Problem of Non-monotonic Reasoning
  • In monotonic logic, the axioms are invariant, even though new information may indicate that certain axioms must be false.
  • Non-monotonic reasoning provides for updating the set of axioms to reflect the best available information (using assert and retract).
slide7
What topics are we covering?
    • Introduction to Prolog
    • Facts
    • Queries
    • Variables
    • Rules
    • Finding solutions
  • What will we be able to do?
    • understanding of fact database
    • able to explain Prolog code
    • able to trace evaluation of a goal
    • able to define simple Prolog relations
how does prolog relate to other languages
How Does Prolog Relate to Other Languages?
  • Wirth:

Programs = algorithms + data structures

  • Kowalski:
    • Algorithms = logic + control

i.e. what we are trying + how we go about

to achieve achieving it

i.e. declarative V's procedural

semantics semantics

where to find prolog at fit
Where to find Prolog at FIT
  • SWI Prolog in FIT Labs
using swi prolog
Using SWI-Prolog
  • We will use a version of Prolog which runs under Linux, Windows xx. You should visit the FIT’s OLT or the following URL, download the appropriate version and get it running on your own PC. The ftp sites are indicated at this URL:

http://www.swi.psy.uva.nl/usr/jan/SWI-Prolog.html

  • use pfe orNotepad as default editor
  • ignore comments in tutorials re

:-state(token...........

This does not apply to SWI Prolog.

  • Note the extensive manual available at the SWI site
using swi prolog contd
Using SWI Prolog (Contd)
  • Editing or Creating a file from within SWI Prolog:

?- edit(myprog).

This edits myprog.pl and then automatically reconsults the file.

  • To exit, use

?- halt.

  • A ‘consulting’ error gives an error message and an ‘error menu’ the meanings of which can be easily discovered.
  • help

?- help. -> a brief ‘help’ file

?- help(get). -> help on the command ‘get’

  • Tracing
    • trace. opens a trace window to enable tracing of the evaluation of the goal (query)
    • notrace.
    • Use 't' to turn on trace during SWI execution.
    • Use 'c' to turn on creep.
using swi prolog contd1
Using SWI Prolog (Contd)
  • When consulting files in subdirectories using SWI Prolog, you need to take care using slashes. A single forward slash or TWO back slashes will be accepted. See examples below:

1 ?- ['a:/a'].

a:/a compiled, 4.72 sec, 2,152 bytes

Yes

2 ?- ['a:\a'].

[WARNING: No such file: user : a:]

No

3 ?- ['a:\\a'].

a:\a compiled, 4.72 sec, 2,152 bytes.

Yes

using swi prolog contd2
Using SWI Prolog (Contd)
  • SWI runs in a window that behaves a little differently from other Windows applications.
  • In particular, you will need to capture output into a file to print and submit for your assignment. One way of doing this is a follows:
    • You can drag the mouse over a SWI screen. Only the first line is highlighted but in fact all lines covered by the mouse are now able to be copied.
    • Then type 'CTRL C'. Now open the window you wish to copy to. Click the mouse to position the copy position. Type 'CTRL V'. The text will appear on one line as 'Enters' are translated to graphics characters. Simple replacing of the graphics characters by 'Enters' will create the text properly.
    • You need to do this carefully to ensure that the text is exactly what I will see when I run your program from the disc you supply with your assignment.
using swi prolog contd3
Using SWI Prolog (Contd)
  • When you load Prolog code using the SWI compiler, you may generally ignore any warnings that refer to 'Singleton Variables'.
    • Most other compilers do not give this warning.
    • If you wish you may get rid of this problem and some others by putting the following at the beginning of every SWI program:

:- style_check(-atom).

:- style_check(-singleton).

:- dynamic(asked/2).

getting started swi prolog assumed
Getting Started (SWI Prolog assumed)
  • 1. (Rarely used) You may enter clauses interactively from the keyboard :

c: [user]. i.e. read clauses from the keyboard

is_integer (0).

etc. a set of Prolog clauses (facts and rules)

etc.

^Z. to exit entry phase and return to query mode.

  • 2. (Commonly used) You may use any DOS editor (such as Notepad, pfe, etc) to form a file of Prolog clauses ( ‘pro1.pl’ in SWI Prolog).
  • 3. To ‘consult’ this file from within Prolog, use

[‘pro1.pl’]. This is a shorthand version of consult('pro1.pl').

slide16
In most versions of Prolog, you may omit the ‘ s if the filename does not contain an extension. This then becomes [pro1]. This is also a shorthand notation for the full form consult(pro1).
  • If you need to edit this file and wish the new definitions of clauses to overwrite the old ones, you need to use:

reconsult(pro).

  • Summary of 4 ways of consulting Prolog clauses into the database

1. [user]. i.e. consult clauses directly from the keyboard or

2. [pro1]. 3 ways of consulting from a file.

3. consult(pro1). or

4. consult(‘pro1.xxx’).

reading programs consult reconsult
Reading programs: consult, reconsult
  • We can communicate our programs to the Prolog system by means of two built-in predicates:
    • consult and
    • reconsult.
  • We tell Prolog to read a program from a file F with the goal:

?- consult( F).

    • The effect will be that all clauses in F are read and will be used by Prolog when answering further questions from the user.
    • If another file is consulted at some later time during the same session, clauses from this new file are simply added at the end of the current set of clauses.
    • [X] is a special notation for consult(X).
    • [file1, file2, file3] is also possible.
    • The built-in predicate reconsult is similar to consult. A goal

?- reconsult( F).

will have the same effect as consult( F) with one exception:

    • If there are clauses in F about a relation that has been previously defined, the old definition will be superseded by the new clauses about this relation in F.
    • The difference between consult and reconsult is that
      • consult always adds new clauses while
      • reconsult redefines previously defined relations. reconsult( F) will, however, not affect any relation about which there is no clause in F.
aspects of declarative languages
Aspects of Declarative Languages
  • Control separate
    • the Prolog system does the matching, backtracking, etc
  • Control can be upgraded (e.g. parallelism) without affecting the source code.
  • Control can extract information in a variety of ways (i.e. not limited to the outcome of one particular procedure) (e.g. append, etc.)
  • less to write since no need to worry about control.
prolog
Prolog

* A goal-directed language - Note

* A logic programming language

  • i.e. all predicates are evaluated to True or False

* A declarative language

  • i.e. you say what you want (see next slide for more details)

* A relational language

* A symbolic language (Therefore useful for AI applications)

  • i.e. suitable for manipulating symbols, cf Lisp

* A Fourth/(Fifth) generation language

* A query-based (conversational) language

* A simple syntax

* A dynamic environment

  • assert new facts and rules
  • retract new facts and rules
  • Solutions found (almost) ‘automatically’

(i.e. the ‘how’ is done for you)

applications of prolog
Applications of Prolog

(Mostly in the area of Artificial Intelligence)

Expert Systems (and shells)

Natural Language Understanding

Language Translation

Symbolic manipulation systems (e.g. equation

solvers, theorem provers, program derivation)

Prototyping Databases in Prolog

Dynamic relational databases

Control and monitoring of industrial processes

VLSI CAD Tools (e.g. editor - implementation is order of magnitude smaller than in imperative languages such as C)

Analysis of VLSI designs at register transfer level

(hardware design tool)

applications of prolog contd
Applications of Prolog (Contd)

Portable Parallelising Pascal Compiler

Natural Language Explanations from Plans

Machine learning

Stream Data Analysis (e.g. of stock market reports)

"Assembly language" for Fifth Generation Language

prolog overview
Prolog Overview
  • Prolog Programming features:

1. declaration of some FACTS about objects and their relationships;

2. declaration of some RULES about objects and their relationships;

      • Note: at this stage ‘programming’ stops and ‘querying’ starts

and

3. asking QUESTIONS about objects and their relationships.

  • As facts and rules are defined Prolog stores them in a database. Then you can (conversationally) ask Prolog questions about the knowledge in the database.
    • data types are CONSTANTS, VARIABLES, or STRUCTURES (see later)
  • 1 and 2 above constitute a Prolog Program
  • 3 is the process of querying the Prolog system once clauses have been consulted.
  • More Simply:

Prolog Programs ~ statements about the world

Prolog queries ~ theorems we would like to have proved

i.e. we tell the Prolog system what is true and ask it to test hypotheses.

defining facts see bratko chapter 1 1
Defining FACTS - See Bratko Chapter 1.1
  • Example of a Fact:

predicate arguments

a predication

likes( john, mary).

relationship objects

(Note: relationships and constant objects must begin with a lower case letter.)

  • Syntax:

- objects separated by commas ','

- fact terminated by full-stop '.'

- objects of relationships within parentheses

'(...)'

facts contd
FACTS - (Contd)
  • Semantics(i.e. Meaning) :

We may decide that the fact has the semantics

"John likes Mary" or indeed

"Mary likes John",

but we must decide on one and stick to it. The names have no meaning to Prolog - they are just symbols to be manipulated.

So make sure you explain via comments the semantics of a relation at the start of its definition!

facts contd1
FACTS - (Contd)

constant constant

female(jane). Jane is a female.

structures

father(john, mary). John is Mary's

father.

gives(john, book, mary).

John gives the

book to Mary.

gives(john, has(cover, green))

Be careful as to what objects the symbols refer.

For example, gold -

valuable(gold).

This is a slightly different interpretation of a fact. Is it a particular piece of gold or is it the element? (or indeed the colour)? The ambiguities must be resolved by the programmer's mind and he should be consistent.

facts contd2
FACTS - (Contd)
  • [As the programmer's mind is volatile and non-transparent it is a good idea for the programmer to actually write down what interpretation is placed upon the symbols and relations.]
a database interpretation of prolog
A ‘database’ Interpretation of Prolog
  • predicate + arguments == record

e.g. book(tanenbaum,a,computer_networks,

prentice_hall,1981,.....).

or more clearly:

book(

tanenbaum,a,

computer_networks,

prentice_hall,

1981,

.

.

...

).

  • A collection of facts is called a database in Prolog.
questions or queries or goals
QUESTIONS (or Queries or Goals)

?- owns (mary, book).

  • Note that some versions of Prolog insist on a ‘?’ to terminate a query.

One possible meaning: Does Mary own a book?

Prolog searches through the database looking for a ‘pattern match’ with:

owns (mary, book)

or something equivalent to it or that it can infer is true.

Two facts match if the predicate and the arguments are the same (as in e.g. above). When a match is found in answer to a question, Prolog answers "yes", otherwise "no".

"yes" means that it was provable by the facts and rules in the database.

"no" means that it was NOT provable by the facts.

Prolog knows nothing directly about the real world - only about what is in its database.

slide29
Database:

likes(joe, fish).

likes(joe, mary).

likes(mary, book).

likes(john, book).

  • Questions:

?- likes(joe, money). ==> no

?- likes(mary, joe). ==> no

?- likes(mary, book). ==> yes

?- likes(john, france). ==> no

?- likes(fred, mary). ==> no

  • Constants

We have been using constant objects

    • e.g. joe, gold, mary, book, ...
    • They remain completely unchanged through the life of the database.
    • They are constant symbols and represent objects in the outside world.
variables
VARIABLES

The questions:

Does John like books ?

Does John like Mary ?

are fairly restricted sorts of questions.

A more interesting question is:

What does John like ?

a variable

Here we are asking for everything that John likes. We will use a variable to represent something that John likes.

Syntax of Variables:

Must start with a capital letter.

Note the following:

Instantiated variables- variables with a value assigned to them, i.e. we have a particularinstance of something that the variable represents

Uninstantiated variables- variables with no value known

slide31
Variables have dynamic scope. This means that they are given one value (when it is found) which it keeps for the duration of that execution within any 1 rule. Once a solution is found then its value is reported and another solution is searched for (if requested). This new search is a new execution and the variable starts out with no value (i.e. uninstantiated). If a search for a solution fails then another search (and another execution)will look for a valid value for the variable.

Given these facts:

likes( john, flowers).

likes( john, mary).

likes( john, golf).

likes( paul, mary).

and the Goal:

?- likes(john, X).

which involves an uninstantiated variable - X, the meaning is:

set X to something John likes, i.e.

instantiate X to something.

Here, Prolog will return in order:

X = flowers;

X = mary;

……...

slide32
i.e., make the question True by giving X a suitable value.

?- likes(john, X).

X = flowers;

X = mary;

X = golf (CR)

No

?-

?- likes(X, mary).

X = john;

...........

X = paul

Think of Prolog as having a marker in the database marking its current match(es).

conjunction of sub goals
Conjunction of Sub-Goals

Goals may be compound goals consisting of a number of sub-goals connected by ‘,’ (the logical AND). In this case, all of the sub- goals need to succeed for the overall goal to succeed.

For example,

?- likes(john, mary), likes(mary, john).

Syntax:

comma (,) means and (conjunction)

Meaning ==>

Does John like Mary and Mary like John?

i.e. Do John and Mary like each other ?

?- likes(mary, X), likes(john, X).

Meaning ==>

Find something liked by both Mary and John.

Prolog tries to match each goal in turn.

Each goal has its place marker.

Prolog attempts a complete match even if it means

retrying the first goal until the database is exhausted.

the and built in predicate
The AND Built-In Predicate ‘,’
  • Note that ‘,’ is really a predicate.

Internally, the implementation of

likes(mary, X), likes(john, X). INFIX Notation

is

‘,’(likes(mary, X), likes(john, X)). PREFIX Notation

In the first case, ‘,’ is acting as an ‘infix’ operator.

In the second case, ‘,’ is acting as a ‘prefix’ predicate - AND.

Other ‘,’s are acting as argument separators.

  • A Note on Operator Notations
    • INFIX a + b
    • PREFIX -a
    • POSTFIX a!
finding solutions for conjoined goals
Finding Solutions for Conjoined Goals
  • Database:

likes(mary, food).

likes(mary, wine).

likes(john, wine).

likes(john, mary).

Prolog processing for

?- likes(mary, X), likes(john, X).

proceeds as follows:

- X uninstantiated, search starts for first sub-goal

- Marker 1 is set and X is instantiated to ‘food’ everywhere in question (i.e. inbothplaces)

- The the second sub-goal becomes likes(john, food). This is sought and the search fails.

- ‘backtrack’ to find another value of X which may succeed.

- X becomes uninstantiated again and marker 1 proceeds from its current position seeking another match for likes(mary, X)

slide36
likes(mary, wine) is found, which satisfies the first goal, so X instantiated to wine.
  • Marker 2 starts from the beginning and finds

likes(john, wine).

  • Since X instantiated to wine satisfies both goals then the overall goal succeeds and X = wine is reported to the user.
  • Prolog then goes on to find any further solutions (relational rather than functional).
another example of compound goals for you to read
Another Example of Compound Goals(For you to read)
  • Assume the database:

1- eats(rhonda, apples).

2- eats(henry,honey).

3- eats(rhonda,icecream).

4- eats(peter,passion_fruit_parfaits).

5- eats(henry,icecream).

6- eats(peter,honey).

?- eats(henry,X),eats(rhonda,X).

sub-goal a sub-goal b

GoalClauseResultInstantiation/Action

a 1 fail

2 success if X = honey,(a) marker at 2

b 1..6 fail backtrack and uninstantiate X,

b is now eats(rhonda,honey)

a 3,4 fail

5 success if X = icecream,

(a) marker at 5

b 1,2 fail

3 success (b) marker at 3

the or predicate
The OR Predicate ‘;’
  • ‘; ‘ is the OR predicate,
    • i.e. it gives the disjunction of 2 or more sub-goals

e.g. likes(X,tennis);likes(X,golf).

(B) (C)

‘or’

Thus, the overall goal is true if (B) is true OR (C) is true.

rules
RULES
  • Rules allow greater flexibility in declaring knowledge. Whereas facts are true in all cases, rules define "facts" that depend upon the truth of other facts. That is, the head of a rule may not always be true - it will depend upon whether its subgoals succeed or not.
  • rule (Definition):

A relationship between a "fact" and a list of sub-goals which must be satisfied for that "fact" to be true

    • a general statement about objects and their relationships.

Syntax:

z :- a, b, c, ………..

i.e. If a and b and c and …, then z or

a and b and c and … z ('implies z')

‘z (is true) if a and b and c and ………… (are all true)’

<conclusion or <requirements or

consequence or :- antecedents or

head> body>

The conclusion of the rule will be true if the requirements are satisfied. The head consists of exactly one predicate, and the body consists of one or more predicates joined with ‘and’ (,) or ‘or’ (;).

undefined sub goal predicates
Undefined sub-goal predicates
  • If SWI Prolog tries to satisfy a sub-goal involving a predicate that does not exist in the database
    • (either because it was never defined or
    • because it was retracted during execution)

then during execution SWI issues a 'Warning', halts execution and goes into 'trace' mode.

Most other versions ignore this and fail.

  • This in some programs using SWI, you need to insert a dummy clause in case this happens.
slide41
Example:

Suppose that John likes everybody. We could say:

likes(john, mary).

likes(john, paul).

:

:

But it would be better to try to say:

“John likes any object if it is a person.”

In prolog, we do this via

lokes(john, X) :- person(X).

  • Other examples of rules (in English):

John buys wine if it is cheaper than beer.

X is a bird if:

X is an animal, and

X has feathers.

X is a sister of Y if:

X is female, and

X and Y have the same parents.

The variable (e.g. X or Y) has to be instantiated to the same object throughout the whole rule.

translating english like rules into prolog
Translating English-like rules into Prolog

John likes anyone who likes wine.

John likes something if that something likes wine.

John likes X if X likes wine.

if

In Prolog:

likes(john, X) :- likes(X, wine).

More examples:

‘and’

likes(john, X) :- likes(X, wine),

likes(X, food).

rules using the disjunctive
Rules Using the Disjunctive ';'
  • ‘; ‘ is the OR predicate, i.e. it gives the disjunction of 2 or more sub-goals

e.g. likes(john,X) :- likes(X,tennis) ; likes(X,golf).

(A) (B) (C)

‘if ‘ ‘or’

Thus, (A) is true if (B) is true OR (C) is true.

  • It is used less frequently than the ‘,’ as two rules with the same LHS achieve the same effect. Thus, the above is equivalent to

likes(john,X) :- likes(X, tennis).

likes(john,X) :- likes(X, golf).

  • Another example:

likes(john, X) :- female(X); likes(X, wine).

finding solutions for goals involving rules but with no variables
Finding Solutions for Goals Involving Rules but with No Variables
  • An example of simple backtracking.
  • Suppose the database contains the following:

boy(john).

boy(marmaduke).

boy(bertram).

boy(charles).

girl(griselda).

girl(ermintrude).

girl(brunhilde).

possible_pair(X,Y) :- boy(X), girl(Y).

  • And the query is:

?-possible_pair(X,Y).

  • The response would be:

X=john, Y= griselda;

X=john, Y= ermintrude;

X=john, Y= brunhilde;

X=mamaduke, Y= griselda;

X=mamaduke, Y= ermintrude;

X=mamaduke, Y= brunhilde;

X=bertram, Y= griselda;

X=bertram, Y= ermintrude;

X=bertram, Y= brunhilde;

X=charles, Y= griselda;

X=charles, Y= ermintrude;

X=charles, Y= brunhilde;

No.

backtracking with sub goals in rules illustrated

S

S

F

S

S

F

S

S

S

S

F

S

F

S

S

YES!

Backtracking with Sub-Goals in Rules Illustrated
  • fred :- a, b, c, d, e, f, g.

The solution would be formed from instantiations formed from the indicated successes.

finding solutions for goals involving rules with variables
Finding Solutions for Goals Involving Rules with Variables

Database:

Facts:

male(albert).

male(edward).

female(alice).

female(victoria).

parents(edward, victoria, albert).

parents(alice, victoria, albert).

Rule:

sister-of(X, Y) :- female(X),

parents(X, M, F),

parents(Y, M, F),

not (X = Y).

Or, using more meaningful names:

sister-of(Sister, Sibling) :- female(Sister),

parents(Sister, Mother, Father),

parents(Sibling, Mother, Father),

not(Sister, Sibling).

slide47
Prolog processing for

?- sister-of(alice, edward).

proceeds as follows:

Step 1 Rule sister-of located and X instantiated to alice and Y set to edward from the goal.

Step 2 The first sub-goal, female(alice), is found in the database of facts so succeeds.

Step 3 Search to match the second sub-goal, parents(alice, M, F). This is found as a fact so succeeds. Variable M is instantiated to victoria, and variable F is instantiated to albert.

Step 4 Prolog now tries to satisfy the third sub- goal so searches for

parents(edward, victoria, albert)

(as Y, M and F have all been instantiated). This fact is found so the sub-goal succeeds.

slide48
Since all sub-goals have now succeeded then the overall goal, sister-of, succeeds (i.e. has been determined to be true) - so Prolog answers yes.
slide49
Prolog processing for

?- sister-of( alice, X ).

proceeds as follows:

Step 1 Rule ‘sister-of’ located and X (of ‘sister-of’ rule) instantiated to alice and Y (from the rule in the program) is set to variable X from the goal. Note that X(goal) and Y variables are both uninstantiated.

Step 2 The sub-goal, ‘female(alice)’, succeeds as before.

Step 3 Variable M is instantiated to ‘victoria’, and variable F is instantiated to albert - as before.

Step 4 Y is unknown, so search for

parents(Y, victoria, albert)

The fact ‘parents(edward, victoria, albert)’ matches this, so Y is instantiated with ‘edward’.

slide50
Step 5 Since all sub-goals have now succeeded then the overall goal, sister-of, succeeds with X being instantiated to edward .

Prolog2 answers:

X = edward.

More(Y/N)? Y

SWI achieves the same effect via

X = edward;

Now Prolog tries to find another solution to sister- of. Steps proceed as from Step 4, with Y uninstantiated again. This time through, Step 4 will match with parents(alice, victoria, albert), so Y (and then X) will be instantiated to alice.

Prolog answers:

X = alice

recursive rule definitions or recursive relations see bratko chapter 1 3
Recursive Rule Definitions (or Recursive Relations) - See Bratko Chapter 1.3

You may be familiar with recursion from experience with other languages.

A relation is expressed in terms of itself.

For example, consider the definition of the ancestor relation.

/* A is the parent of B in parent(A,B)*/

/* A is the ancestor of B */

ancestor(A,B) :- parent(A,B).

ancestor(A,B) :- parent(C,B), ancestor(A,C).

form dangers of a recursive procedures
Form/Dangers of a Recursive Procedures
  • Forms:

Any recursive procedure must have:-

(i) a nonrecursive clause defining the base case (such as the first rule of 'ancestor')

(ii) a recursive rule where the first subgoal generates new argument values followed by recursive subgoals using the new argument values (such as the second rule of 'ancestor')

  • Dangers

Take care to avoid endless loops during recursion:

Circular definitions:

parent(X,Y) :- child (Y,X).

child(A, B) :- parent (B,A).

Left Recursion

i.e. when a rule causes the invocation of a goal that is essentially equivalent to the original goal

person(X) :- person(Y), mother (X,Y).

person(adam).

?- person(A).

the meaning of prolog programs semantic models of prolog
The Meaning of Prolog Programs(Semantic Models of Prolog)
  • Declarative Model

The meaning of a Prolog predicate is considered as a definition of a static relation between terms (the arguments).

  • Abstract Machine Model
    • This is a behavioural view of the Prolog interpreter evaluating Prolog language constructs.
    • It is similar to the behavioural semantic models of other programming languages - which at the base level are imperative.
    • This model accounts for all extra-logical effects (i.e. input/output and control side-effects).
    • It may be tracked via trace.
towards a formal definition of prolog data objects and prolog syntax
Towards a Formal Definition of Prolog - Data Objects (and Prolog Syntax)
  • Programs are built from terms.
  • A term may be
    • constant, or
    • variable, or
    • structure (see later)
  • A term is written as a sequence of characters
    • AB..Zab..z01..9
    • +-*/\^<>=`~:.?@#$&
  • Characters are treated as integers between 0 and 127, i.e. the decimal equivalent of the ASCII code.
  • A constant is a name of
    • an object or
    • a relationship
  • A constant may be
    • an atom
    • an integer
    • ?- :-
      • The list above may depend on the implementation, e.g. the range of integers.
prolog syntax continued
Prolog Syntax(Continued)
  • An atom is formed by
    • letters and digits
      • begins with a lowercase letter and may use ‘_’ for readability
    • symbols
      • e.g. =, -->
  • A variable has a name beginning with
    • (1) an uppercase letter, or
    • (2) the character ‘_’
      • e.g. _abc, _16
      • _ by itself is called the anonymous variable’ (see later)
prolog a partial syntax omit the next 3 slides for itb742 at kg
Prolog - A Partial Syntax(Omit the next 3 slides for ITB742 at KG)
  • Program
  • Clause
  • Rule
  • Fact

Clause

Rule

Fact

, or ;

.

Predication

:-

Predication

.

Predication

prolog a partial syntax cont

atom

integer

Prolog - A Partial Syntax (cont)

,

  • Predication
  • Term
  • Constant
  • Atom (simple)

(

)

Predicate

Argument

constant

variable

structure

'

character

'

letter

lower case letter

digit

an example of a predication

predicate constant

arguments

(likes 'Mike Jones' cars) in Predicate Calculus

An example of a predication
  • e.g. predication

likes('Mike Jones', cars). in Prolog

data objects in prolog
Data Objects in Prolog

data objects

simple objects structures

constants variables

atoms numbers

(usually integers

with most versions

of Prolog)

structures
Structures

Structures (or Compound Objects - see earlier)

Compound objects can be regarded and treated as single objects.

A structure is a single object which consists of a collection of other objects called components.

They allow a group of related information to be treated as a single object.

Syntax:

<functor> ( <components> ... )

where each component can itself be a structure.

Components are separated by commas (,).

<functor> is the name of the structure.

Prolog programs are made of terms. Terms can be constants, variables or structures. (cf. Scheme)

Example:

structure components

owns(john, book(wuthering-heights, author(emily, bronte) ) ).

functor components

structures contd
Structures (Contd)
  • Creating and Accessing Components of General Structures using a 'built-in' predicate (our first):
    • functor(T,F,N) (a ‘built-in’ predicate)

"T is a structure with functor F and arity (number of components) N."

If T is instantiated it must be an atom, i.e.

an atom is a structure with arity 0

?- functor (likes (john, money), F, N).

N = 2,

F = likes.

?- functor(a+b,F,N). a+b ~ +(a, b) internally

N = 2,

F = +

recursive data structures
Recursive Data Structures
  • The name of the structure is called the functor.
  • The number of objects contained by the structure is its arity.
  • Both functor name and arity must match for the structures to be able to match.
  • The objects (or components) contained within a structure can be any type of objects - simple (e.g. numbers or symbols), complex (i.e. other structures) and even recursive (objects of the same structure).
slide63

tree(tree(tree(end,2,end),3,end),4,

tree(tree(end,5,end),6,end) )

  • You don’t need pointers to have a recursive data structure!
  • For example: (tree)

left root right

  • This is equivalent to the tree:

tree-4

tree-3 tree-6

tree-2 end tree-5 end

end end end end

anonymous variables
Anonymous Variables

If you are not interested in the values of particular arguments, then you can just "ignore" them using anonymous variables. Anonymous variables will match with anything, i.e. they act as ‘place holders’.

NB: Two or more uses of anonymous variables in a clause do not instantiate to the same object - i.e. each one is distinct and separate (even though they are represented by the same sign).

For example,

?- owns(john, book( _ , author( _ , bronte) ) )

may mean:

Does John have any book by any of the Bronte sisters?

unification a form of pattern matching
Unification A Form of Pattern Matching

The purpose of the Prolog unification process is to:

(i) decide which clause to invoke

(ii) pass the actual parameters to the clause

(iii) deliver the results

Unification is a bi-directional process - i.e. information can flow either way (i.e. either by an input parameter or by an output parameter (but not both!)) depending on usage.

e.g. If owns(a, b, X, P).

is an item in the database,

and it is ‘unified’ with the query

owns(A, B, tom, Q).

then A is instantiated to a,

B is instantiated to b,

X is instantiated to tom, and

P and Q ‘share’

from this time onwards.

See details following.

unification rules
Unification Rules

Unification (a special from of pattern matching) obeys the following Rules:

1. A variable unifies with a constant or a structure.

e.g. X = joan ==> X instantiated to joan

2. A variable unifies with a variable.

e.g. X = Y ==> X and Y ‘share’ the same value.

3. The anonymous variable (_) unifies with anything. e.g. alice = _

4. A constant unifies with a constant if they are identical.

e.g. alice = alice ==> true

10 = 10 ==> true

5. A structure unifies with a structure if the structure names (or functors) are the same and if the arguments can all be unified.

e.g. father(albert) = father(X)

==> X = albert

slide67
[NB: The structures typically have a number of arguments and they must be unified in a "do-able" order.]
  • [NB: Pattern-matching for lists (e.g. [H|L]) is as described above after converting the list notation to standard syntax (i.e. the dot "." structure).]
evaluating a prolog query
Evaluating a Prolog Query

Evaluation can be understood as a recursive cycle of unification (pattern matching) and subgoal evaluation.

Evaluation is goal-directed.

Evaluation is triggered by a query (initial goal).

Evaluation descends as deep as necessary into the structure of the program to find facts that validate the query.

It returns having proved or failed to prove the goal, with zero or more instantiations.

The search space for solutions consists of a tree (with possibly infinitely long branches !). Prolog searches this tree using a depth-first strategy.

You can quickly see that Prolog may start looking for a solution down an infinite-length branch and never return - while the solution is sitting in the next branch along. This is why we must be careful with the order of our subgoals in a rule.

slide69
Prolog's search strategy is not perfect. There may be solutions but Prolog may fail to find them.

Prolog is limited. It is a restricted class of logic programming in order to be executable.

Parallel implementations of Prolog may provide a better implementation of logic programming.

steps of evaluation
Steps of Evaluation

1. Find relevant Clause:

When a goal (query/question) is entered by the user, the goal is activated.

The interpreter searches through the clauses (facts and rules) for the first clause whose head unifies with the query.

For the goal to unify with the head of a clause, both must have the same predicate name and same arity (number of arguments), and all arguments of both must unify.

2. Evaluate subgoals:

When a clause matches, it is activated and each of the subgoals in the body of the clause is evaluated in the same way as the original query (i.e. recursively).

If the body is empty (i.e. a fact) then it succeeds.

slide71
3. Backtrack:

If no clauses match then the interpreter backtracks.

It returns to the last successful subgoal, undoes any bindings (instantiations) , and begins looking for any more matching clauses. (A place marker is associated with each subgoal.)

4. Report Result(s):

On success, Prolog prints out the values of any variables in the query; or yes (true) if there were no variables.

On failure, ==> no

declarative vs procedural meaning of prolog programs
Declarative vs Procedural Meaning of Prolog Programs

Consider the Prolog rule:

P :- Q, R.

i.e. if (q and r) then p

The Declarative Meaning:

“P is true if Q is true and R is true.”

The Procedural Meaning:

“To solve problem P, first solve the sub-problem Q and then solve the sub-problem R.”

or

“To satisfy P, first satisfy Q, and then satisfy R”.

the meaning of prolog programs
The Meaning of Prolog Programs

Procedural Model

A Prolog program is executed (computed) according to the following algorithm:

1. To execute a goal (original query or sub-goal), match it against the head of a clause (fact or rule) and then execute the sub-goals in the body of the clause.

2. If no match can be found - backtrack. That is, go back to the most recently executed goal and seek another solution for it.

3. Execute goals in left-to-right order.

4. Try clauses in top-to-bottom order.

Note that the control strategy is goal-driven i.e. information is found in order to prove (or deduce) the goal.

1. To execute a goal (original query or sub-goal), match it against the head of a clause (fact or rule) and then execute the sub-goals in the body of the clause.

2. If no match can be found - backtrack. That is, go back to the most recently executed goal and seek another solution for it.

3. Execute goals in left-to-right order.

4. Try clauses in top-to-bottom order.

Note that the control strategy is goal-driven i.e. information is found in order to prove (or deduce) the goal.

representation of lists lists in prolog
Representation of Lists (Lists in Prolog)
  • Definition: A list is either
      • an empty list or
      • it is a structure that has two components
        • the Head (the first element of the list) and
        • the Tail (the list of remaining elements)
  • Lists are structures using the dot "." functor (cf 'cons' in Lisp for ITB442 students).
    • functor([a,b,c],F,N).

N = 2,

F = . (the functor for generating lists)

This result comes from the internal representation of the list above as .(a, [b, c]).

  • .(H,T) is the base notation but it may also be written as H.T (as . is also defined as an operator) or [H|T].
  • This last form is the most common.
    • In general a list is written as:

[H | T]

  • Note: [a, b, c] is represented internally as .(a, [b,c])
    • It may also be referenced as [a | [b.c]] using the [H | T] form.
notation
[ , , , , ] Notation
  • This important class of data structure is given a convenient notation as shown below, but at the base level is just a structure (a compound term).
  • Lists may also represented as a number of comma-separated elements surrounded by square brackets.

e.g.[ a, b, c ]

This is written in standard syntax as: .(a,.(b,.(c,[])))

  • You can also access the second and third elements by splitting the tail:-
    • [ Head1, Head2 | Tail ] unified with [ a, b, c ] gives

Head1 = a, Head2 = b, Tail = [c]

    • [a,b,c,d] = [a|[b,c,d])

= [a,b | [c,d]).

= [a,b,c | [d]).

  • [a,b,c]= .(a,[b,c]) = a.[b,c]

= .(a,.(b,[c])) = a.(b.[c])

= .(a,.(b,.(c,[]))) = a.(b.(c.[]))

slide76
A Second Definition of a list:

A list is either the atom [ ], representing the empty list, or a compound term with functor '.' and two arguments which are respectively the head and tail of a list.

It is an ordered sequence of elements.

  • Strings

Strings are implemented as lists of ASCII integers, e.g.

“systems” = [115,121,115,116,101,109,115]

trees
Trees
  • A structure naturally corresponds to a tree or sub-tree
    • tutors210(ruth, john, mike).

may be thought of as the following tree:

tutors210 root ~ functor

branches ~components

ruth john mike

  • Using a tree structure to show the syntax of an English sentence:

sentence (noun, verb_phrase (verb, noun))

sentence

noun verb_phrase

(Jim)

verb noun

(hit) (Bill)

lists as trees
Lists as Trees
  • Lists are special kinds of trees.

[a] ~ .[a,[]) .

a []

[a,b,c] ~ .(a,.[b,c]) .

a [b,c]

~ .(a,.(b,[c])) .

a .

b [c]

~ .(a,.(b,.(c,[]))) .

a .

b .

c []

examples of using lists
Examples of Using Lists
  • ?- [user]. 3 arguments 4 arguments

p([1,2,3]).

p([the,cat, sat,[on,the,mat]]).

^Z

?- p([X|Y]).

X = 1,

Y = [2,3];

X = the,

Y = [cat,sat,[on,the,mat]]

Yes

?-p([_ ,_ ,_ ,[_|X]]).

X = [the,mat]

Yes

list processing
List Processing
  • Lists can be processed in much the same way as in Lisp (i.e. with recursive definitions).

** But note the difference between a functional definition and a relational definition.

    • a functional definition
      • specifies the output (result) in terms of the input (arguments)
    • a relational definition
      • specifies the relationship between a number of objects (the arguments)
    • which terms are input and output is determined by use

e.g. member(a,[a,b,c]).----------> Yes member(a, X). ----------> ??? member(Y, X). -----------> ???

It is easy to see that the first query is meaningful but the latter 2 are not.

examples of list relations
Examples of List Relations
  • Consider, for example, member and append:

/* X is an element in the list */

member(X,[X|_]).--------------------- 1

member(X,[_|Y]) :- member(X,Y).------ 2

If the following query is presented

member(d,[a,b,c,d,e]).

the recursive calls are as follows:

1. Fail

2. Success - member(d,[a,b,c,d,e]).

2. Success - member(d,[ b,c,d,e]).

1. Fail

2. Success - member(d,[ c,d,e]).

1. Fail

2. Success - member(d,[ d,e]).

1. Success !!!

some more list relations
Some More List Relations

/* 3rd argument is 2nd appended to 1st.

Bratko calls this ‘conc’ . */

append([],L,L).

append([X|L1],L2,[X|L3]) :- append(L1,L2,L3).

* last element of a list */

last(X,[X]).

last(X,[_|Y]) :- last(X,Y).

/* two consecutive elements in a list */

nextto(X,Y,[X,Y|_]).

nextto(X,Y,[_|Z]) :- nextto(X,Y,Z).

/* redefinitions using append */

last(El,List) :- append(_,[El],List).

nextto(El1,El2,List) :- append(_,[El1,El2|_],List).

member(El,List) :- append(_,[El|_],List).

X L1 L2 X L3

slide83
/* two lists which are the reverse of each other:

version 1

e.g. rev([a, b, c],X). gives X = [c, b, a] */

rev([],[]).

rev([X],[X]).

rev([H|T],L) :- rev(T,Z), append(Z,[H],L).

/* version 2

iterative solution - uses auxiliary relation and accumulating argument */

/* second arg to revzap is an accumulator */

rev2(L1,L2) :- revzap(L1,[],L2).

revzap([X|L],L2,L3) :- revzap(L,[X|L2],L3).

revzap([],L,L).

/* the first list is a prefix of the second list*/

prefix([],_).

prefix([X|L],[X|M]) :- prefix(L,M).

operator notation
Operator Notation
  • The form of all structures is prefix form, e.g.

=(X, Y)

However, a number of operations are provided in infix form for convenience, e.g.

X = Y.

  • Equals X = Y

(a) if X and Y are both uninstantiated, it means that they will share a value when either variable is instantiated (and then will succeed).

(b) X = Y will succeed if X and Y are instantiated and have the same value.

(c) X = Y will fail if X and Y are instantiated and if X has a different value from Y.

(d) X = Y in the case that Y is instantiated and X is not; will succeed and X is assigned the value of Y. The reverse of this fails.

  • Note: X = Y will not cause evaluation of Y if Y is an arithmetic expression, e g.

the sub-goal X = Y + 1

will result in the instantiation of

+(Y,1) to X

other operators
Other Operators
  • not Operator

not(X = Y) will succeed when X = Y fails.

We would use 'not equals' or <> to correct our sister-of example to eliminate self-sistering.

sister-of( X, Y ) :- female(X), parents(X, M, F), parents(Y M, F), not( X = Y ).

  • Note, with some versions of Prolog,

not(X = Y) is written as /(X = Y)

  • Other Relational Operators

All the usual ones: <, <=, = , >, >=, <>

properties of prolog operators
Properties of Prolog Operators
  • Functors may be written as operators for ease of reading.

+(x,*(y,z)). vs x+y*z

  • Operators have 3 properties:
    • (1) position
      • prefix -x
      • infix a+b
      • postfix x!
    • (2) precedence
      • Each operator has a 'precedence class', i.e. an integer in the range 1..max. The lower the number, the higher is the precedence!
    • (3) associativity
      • left associative
      • right associative

(i) (ii)

associativity continued
Associativity Continued
  • What does 8/2/2 mean? and 2^3^4 ??

(8/2)/2 = 2 or

8/(2/2) = 8 ??

  • Definition: 'A left associative operator must have the same or lower precedence operations on the left and lower precedence operations on the right.'
      • Thus, 8 / (2 / 2) is ruled out because operator (i) requires its secondoperand to have an operator which is strictly lower in precedence

(ii) is not strictly lower than (i).

Thus (8/2)/2 is the correct interpretation.

declaring operators
Declaring Operators
  • To declare operators, you supply a 'picture' of the operator use which defines its properties.
    • For infix operators, these are:
      • xfx, xfy, yfx, yfy

left associative

right associative

    • For prefix operators:
      • fx, fy
    • For postfix:
      • xf, yf
  • Associativity
    • 'y' --> the argument can contain operators of the same or lower precedence than this operator
    • 'x' --> the argument must contain operators of strictly lowerprecedence than this operator

Thus yfx is left associative

slide89
Examples of built-in operator declarations:
    • op(31, yfx, -). left associative

op(31, yfx, +).

op(21, yfx, /).

op(21, yfx, *).

op(60, fx,not).

op(253, fx,',').

op(255, fx,'?').

user defined operator definitions
User-defined Operator Definitions
  • User-defined operators may be defined in the same way:
    • op(800, xfy, <===>). logical EQUIVALENCE

op(700, xfy, V). logical OR

op(600, xfy, &). logical AND

op(500, fy, ~). logical NOT

    • Thus, the following now becomes correct Prolog syntax!

~ (A & B) <===> ~A V ~B.

which you may recognise as de Morgan's Law,

ab’ = a’ + b’

arithmetic using is
Arithmetic(using 'is')
  • Most versions of Prolog have all the usual arithmetic operations, and expressions are evaluated in normal mathematical fashion - i.e. infix and follow precedence.
  • NB: An expression can only be evaluated if all variables are bound at the time of evaluation.

e.g. A is 22/Z

If Z has already been bound to 7 then the expression is calculated to yield 3.14285, and this approximate value is then bound to variable A and the sub-goal succeeds.

However, if we have A = 22/Z, then A is bound to 22/7, which is, in fact, the exact value of the expression as opposed to the previous approximation.

example of arithmetic
Example of arithmetic:
  • Here is an example of a rule in English:

The population density of country X is Y if:

The population of X is P, and

The area of X is A, and

Y is calculated by dividing P by A.

  • In Prolog, the rule would be expressed like this:

density(X, Y):- pop(X, P), area(X, A), Y is P/A.

  • Note that P and A must be instantiated before the calculation
    • - so the expression can be calculated and the resulting value bound to Y.
    • (Also works on characters, strings and symbols.)
definition of p is q
Definition of'P is Q'

P Q Result

instantiated instantiated T or F

instantiated un-instantiated F

un-instantiated instantiated P Q

un-instantiated un-instantiated P and Q 'share'

The only difference between the table above and the one for '=' is in line 3 where the latter returns 'F'.

(i.e. assignment, and Q is evaluated if it is an expression)

more on equality
More on Equality
  • The goal X = Y succeeds as follows:
      • If x is un-instantiated and Y is any object, X is instantiated to Y.
      • Integers and atoms are always equal to themselves.
      • 2 structures are equal if they have the same functor and member of arguments, and all corresponding arguments are equal.
      • If both X or Y are uninstantiated, it succeeds and X and Y 'share'.

All arguments atoms:

?-rides(clergyman, bicycle) = rides(clergyman,X).

X = bicycle

Yes

Arguments are a mixture of atoms and

variables:

?- a(b,C,d(e,F,g(h,i,J))) = a(B,c,d(E,f,g(H,i,j)))

H = h,

J = j,

B = b,

C = c,

E = e,

F = f

yes

the ‘=‘ causes unification to be carried out

slide95
All arguments are variables:

?- point(X,Y,Z)=point(X1,Y1,Z1).

Z1 =_66,

X = _24,

Y1 = _45,

Y = _45, i.e. X and X1 ‘share’, etc

Z = _66,

X1 = _24

yes

controlling backtracking via the cut
ControllingBacktracking - via the 'cut'
  • controlling the execution of a program
    • through the ordering of clauses and goals
    • using 'cut' for preventing backtracking
  • The cut
    • extends the expressive power of Prolog and
    • enables the definition of a kind of negation, called 'negation as failure'
      • associated with the 'closed world assumption'.
the cut
The ‘cut’ - !
  • The ‘cut’ is a built-in predicate with functor (or name - see later) ‘!’ and no components.
  • It forces all other alternatives to be discarded.
    • Hence an attempt to resatisfy and goal between the parent goal and the ‘cut’ goal will fail.
    • fred :- a, b, c, !, d, e, f.

This and all other

rules for fred now

fail.

!

a more precise definition of the cut
A more precise definition of the cut
  • Let us call the 'parent goal' the goal that matched the head of the clause containing the cut.

When the cut is encountered as a goal, it succeeds immediately, but it commits the system to all choices made between the time the 'parent goal’ was invoked and the time the cut was encountered.

All the remaining alternatives between the ‘parent goal’ and the cut are discarded.

  • To clarify this definition consider a clause of the form:

H :- B1, B2, ... , Bm, !, ... , Bn.

Let us assume that this clause was invoked by a goal G that matched H. Then G is the parent goal.

At the moment that the cut is encountered during back-tracking, the system has already found some solution of the goals B1, ... , Bm. When the cut is executed, this (current) solution of B1, ..., Bm becomes frozen and all possible remaining alternatives from other rules for it are discarded.

slide99
Also, the goal G now becomes committed to this clause:
  • any attempt to match G with the head of some other clause is precluded,
    • i.e. all attempts to satisfy H fail.
applying these rules to an example
Applying these rules to an example:
  • C :- P, Q, R, !, S, T, U.

C :- V.

A :- B, C, D.

?- A.

  • Backtracking will be possible within the goal list P, Q, R; however, as soon as the cut is reached via backtracking right to left, all alternative solutions of the goal list P, Q, R are suppressed.
  • The alternative clause about C,

C :- V.

will also be discarded.

  • Backtracking will still be possible within the goal list S, T, U. The 'parent goal' of the clause containing the cut is the goal C in the clause:

A :- B, C, D.

Therefore the cut will only affect the execution of the goal C.

On the other hand, it will be 'invisible' from goal A. So automatic backtracking within the goal list B, C, D will remain active regardless of the cut within the clause used for satisfying C.

an example of using
An Example of using !

/* This uses the cut to terminate a ‘Generate and Test’ Process

pro19 - This program carries out integer division and uses the is_integer predicate of pro13.*/

is_integer(0).

is_integer(X):-is_integer(Y),X is Y+1. /* This is the ‘generator’. */

divide(N1,N2,Result):-

is_integer(Result),

Product1 is Result*N2,

Product2 is (Result+1)*N2, /*This is the ‘tester’. */

Product1 =<N1,

Product2>N1, !.

/* pro13 - The cut indicates that once the first solution is found, there is no point looking for others.*/

Execution:

?- ['pro19.'].

pro19. consulted

?- divide(34, 6, X). - This is the result with the 'cut' in the program.

X = 5;

no

If the cut is omitted:

?- ['pro19.'].

pro19. consulted

?- divide(34, 6, X).

X = 5;- This is the result with the 'cut' omitted from the program.

!!!!!!!!!!!!!!! Infinite Loop - need to reset machine

negation as failure
Negation as Failure
  • 'Mary likes all animals but snakes'. How can we say this in Prolog?

It is easy to express one part of this statement: Mary likes any X if X is an animal.

This is in Prolog:

likes(mary, X) :- animal(X).

  • But we have got to exclude snakes. This can be done this way:

If X is a snake then ‘Mary likes X' is not true, otherwise if X is an animal then

Mary likes X.

  • That something is not true can be said in Prolog by using a special goal, fail, which always fails, thus forcing the parent goal to fail.
    • The above is translated into Prolog, using fail, as follows:

likes(mary, X) :- snake( X), !, fail.

likes(mary, X):- animal( X).

The first rule here will take care of snakes: if X is a snake then the cut will prevent backtracking (thus excluding the second rule) and fail will cause failure.

slide103
These two clauses can be written more compactly as one clause using the ‘cut/fail’ combination again:

likes(mary, X):-

snake(X), !, fail

;

animal( X).

the unary predicate not
The UnaryPredicate 'not'
  • These examples indicate that it would be useful to have a unary predicate 'not' such that

not( Goal)

is true if Goal is not true

  • not(Goal) is true if Goal is not true

Definition:

If Goal succeeds then not( Goal) fails, otherwise not( Goal) succeeds.

  • This definition can be written in Prolog as:

not( P) :-

P, !, fail

;

true. (true always succeeds)

  • not is usually also defined as a prefix operator, so that we can also write the goal

not(snake(X)) as: not snake( X)

  • Note: not defined above as failure does not exactly correspond to negation in mathematical logic.
    • This difference can cause unexpected behaviour if not is used without care.
slide105
not is a useful facility and can often be used place of cut. e.g.,

likes(mary, X) :-

animal(X),

not snake(X).

    • more natural than !, fail
problems with cut and negation
Problems with cut and negation
  • The advantages of using cut:
    • (1)With cut we can often improve the efficiency of the program. The idea is to explicitly tell Prolog: do not try other alternatives because they are bound to fail.
    • (2)Using cut we can specify mutually exclusive rules; so we can express rules of the form:

if condition P then conclusion Q,

otherwise conclusion R

In this way cut enhances the expressive power of the language.

  • A disadvantage of using cut:
    • If there is no cut in the program we can change the order of clauses and goals, and this will only affect the efficiency or termination of the program, not the declarative meaning.
    • On the other hand, in programs with cuts, a change in the order of clauses may affect the declarative meaning. This means that we can get different results.
a disadvantage of using cut an example omit kg
A Disadvantage of Using cut - an example(Omit KG)
  • Examine:

p :- a, b

;

c.

The declarative meaning of this program is:

‘p is true if and only if a and b are true or c is true.'

This can be written:

p <===> (a & b) v c

We can change the order of the two clauses and the declarative meaning remains the same.

  • Let us now insert a cut:

p :- a, !, b.

p :- c.

The declarative meaning is now:

p <===> (a & b) v (~a & c)

If we swap the clauses,

p :- c.

p :- a, !, b.

then the meaning becomes:

p <===> c v (a & b)

When we use the cut facility we have to pay more attention to the procedural aspects.

green cuts and red cuts
‘Green’ cuts and ‘Red’ cuts
  • If the cut has no effect on the declarative meaning, cuts of this type are sometimes called 'green cuts'
    • When reading a program, green cuts can simply be ignored.
  • Cuts that do affect the declarative meaning are called ‘red’ cuts.
    • Red cuts are the ones that make programs hard to understand, and they should be used with special care.
  • Negation is just a special (more restricted) way of using cut.
    • when cut is used in combination with fail
    • prefer to use not instead
not may also cause problems
‘not’ may also cause problems
  • not, as defined here, does not correspond exactly to negation in mathematics.
  • If we ask,

?- not human( mary).

Prolog will probably answer 'yes'. But this should not be understood as Prolog saying

'Mary is not human'.

What Prolog really means to say is:

    • 'There is not enough information in the program to prove that Mary is human'.
  • Such reasoning is based on the so-called ‘closed world assumption’.
    • “The world is closed in the sense that everything that exists is in the program or can be derived from the program.“
  • We do not normally assume that the world is closed.
    • With not explicitly entering the clause

human(mary).

into our program, we do not normally mean to imply that Mary is not human.

closed world assumption cwa
Closed World Assumption- CWA
  • Prolog can prove truth but not falsity.
    • i.e. Prolog can not represent negative information.
  • This is based on the assumption that Prolog knows all there is to know (i.e. that there is a closed world).
  • An assertion A might fail. This does not mean that A is definitely false; it simply means that Prolog cannot prove that it is true.
  • Very few assertions in Prolog are definitely false (e.g. chalk = cheese, 2 > 3).
  • Failure means either unknown or false.
  • Prolog ignores the difference between unknown and false for convenience.
negation and the cwa
Negation and the CWA
  • The closed world assumption obliges Prolog programmers to encode all relevant information for their particular problem.
  • Prolog provides negation in the form of not.
  • ‘not’ negates the assumed truth of an assertion.
  • Negation of unknown is taken to be true!
  • This may lead to misleading conclusions such as when using the following database:

person(fred).

person(mary).

friendly(fred).

friendly(mary).

friendly(gremlin).

alien(X) :- not(person(X)),

not(friendly(X)).

If we try the query:

?- alien(john).

yes

(This succeeds primarily because ‘john’

is not mentioned in the database.)

an example of the care needed with not
An Example of the care needed with ‘not’

good-standard(jeanluis).

expensive(jeanluis).

good-standard(francesco).

reasonable(Restaurant) :- not expensive(Restaurant).

If we now ask

?- good-standard(X), reasonable(X).

then Prolog will answer:

X = francesco

If we ask apparently the same question

?- reasonable(X), good-standard(X).

then Prolog will answer:

no

The key difference between both questions is that the variable X is, in the first case, already instantiated when reasonable(X) is executed,

whereas at that point X is not yet instantiated in the second case.

communication with files
Communication with 'files'
  • As well as the interactive method of using Prolog, basic communication methods are needed in the following areas:
    • input of data in forms other than questions - for example, in the form of English sentences
    • output of information in any format desired, and
    • input from and output to any computer file or device and not just the user terminal.
  • A program can, in principle, read data from several input files, also called input streams, and output data to several output files, also called output streams.
  • At any time during the execution of a Prolog program, only two files are 'active':
    • one for input and one for output
    • i.e. current input stream and the current output stream respectively
    • At the beginning of execution, these two streams correspond to the user's terminal.
  • The current input stream can be changed to another file, Filename, by the goal:

see(Filename) (This is equivalent to ‘<‘ in DOS or Unix.)

  • Such a goal succeeds (unless there is something wrong with Filename) and causes, as a side effect, that input to be switched from the previous input stream to Filename.
input from a file see seeing seen
Input from a file - see, seeing, seen
  • Example of using see:

...........

see(file1), /* open for reading */

read_from_file(Information),

seen(file1), /* Close file */

see(user), /* keyboard */

..........

  • The goal 'seen' closes the current input file.
  • seeing(X)
    • If X is instantiated = “Is file X the current device?”
    • If X is uninstantiated = “What file is the current device?” **
      • i.e. returns the name of the current default for input
output to a file tell telling told
Output to a File - tell, telling, told
  • The current output stream can be changed by a goal of the form:

tell(Filename)

    • where X is instantiated to a file name:
      • If file existing = open and append to it **
      • If file not existing = create **
    • If X is uninstantiated, error.

A sequence of goals to output some information to file3, and then redirect succeeding output back to the terminal is:

...........

tell(file3), /* open for writing */

write_on_file(Information),

told(file3),

tell(user),

..........

  • The goal 'told' closes the current output file.
  • telling(X)
    • If X is instantiated = “Is file X the current device?”
    • If X is uninstantiated = “What file is the current device?” **
      • i.e. returns the name of the current default for output
    • * These are 'normal' uses of tell and telling.
slide116
We will assume here that files can only be processed sequentially.
  • If a request for reading is made at the end of a file, then the information returned by such a request is the atom 'end-of-file' (^Z in DOS, ^D in UNIX).
  • All files are 'text-files', i.e. files of characters.
processing a file of terms
Processing a file of terms
  • A typical sequence of goals to process a whole file, F, would look something like:

..., see(F), processfile, see(user), ...

Here processfile is a procedure to read and process each term in F, one after another, until the end of the file is encountered.

  • A typical schema for processfile is:

processfile :-

read(Term), % Assuming Term not a variable

process(Term).

process(end-of-file) :- ! . % All done

process(Term) :-

treat(Term), % Process current item

processfile. % Process rest of file

Here treat(Term) represents whatever is to be done with each term.

character and term input output
Character and Term Input/Output
  • Character Input/Output
    • One way of viewing a file is to consider the character as the basic element of the file. Accordingly, one input or output request will cause a single character to be read or written.
    • Predicates for this are
      • get,
      • get0 and
      • put
  • Term Input/Output
    • The other way of viewing a file is to consider Prolog terms as basic building blocks of the file. So each input/output request of this type would transfer a whole term from the current input stream or to the current output stream respectively.
    • Predicates for transfer of terms are
      • read and
      • write
outputting characters put
Outputting Characters - put
  • A character is written on the current output stream with the goal

put(C)

where C is the ASCII code (a number between 0 and 127) of the character to be output.

    • always succeeds and a ‘side effect’ prints its argument as a character on the terminal
    • e.g.

?- put(65), put(66), put(67).

would cause the following output:

ABC

    • 65 is the ASCII code of 'A', 66 of 'B', 67 of 'C'.

e.g printstring([]).

printstring([H|T]) :- put(H), printstring(T).?- printstring(“Charles V abdicated at Brussels”).Charles V abdicated at Brussels

reading characters get0 and get
Reading Characters - get0 and get
  • get0(C) (i.e. get zero)
    • A single character can be read from the current input stream by the goal
    • get0 will read newline,space, etc as characters
    • This causes the current character to be read from the input stream, and the variable C becomes instantiated to the ASCII code of this character.
  • get(C)
    • A variation of the predicate get0 is get, which is used for reading non-white space characters.
    • the goal get(C) will cause the skipping over of all non-printable characters
example
Example
  • Define a procedure, squeeze, to do the following:
    • read a sentence from the current input stream, and
    • output the same sentence reformatted so that multiple blanks between words are replaced by single blanks.
    • For simplicity, we will assume that any input sentence processed by squeeze ends with a full stop and that words are separated simply by one or more blanks, but no other character.
  • If the input were:

The robot tried to pour wine out of the bottle.

The goal squeeze would output this in the form:

The robot tried to pour wine out of the bottle.

slide122
The squeeze procedure will
  • read the first character,
  • output this character, and then
  • complete the processing depending on this character.
  • There are three alternatives that correspond to the following cases:
    • the character is either a full stop, a blank or a letter. The mutual exclusion of the three alternatives is achieved in the program by cuts:

squeeze :- /* Note: a predicate with no arguments! */

get0(C),

put(C), /* will output 1st blank in a series of blanks*/

dorest(C).

dorest(46) :- !. /* 46 is ASCII for full stop, all done */

dorest(32) :- !, /* 32 is ASCII for blank */

get(C), /* Skip white space after a space. */

put(C), /* Skip other remaining blanks */

dorest(C).

dorest(Letter) :-

squeeze.

slide123
read
  • The built-in predicate read is used for reading terms from the current input stream.
  • The goal

read(X).

will cause the next term, T, to be read, and this term will be matched with X.

    • If X uninstantiated, then X will become instantiated to T, i.e. the next ‘term’ terminated by ‘.’ + a non-printing character, and ‘read will succeed. This is the more usual use.
    • If X is instantiated, then read(X) succeeds if X matches what is read and fails otherwise.
  • The predicate read is deterministic, so in the case of failure, there will be no backtracking to input another term.
  • Each term in the input file must be followed by a full stop and space or carriage-return.
  • If read(X) is executed when the end of the current input file has been reached, then X will become instantiated to the atom 'end-of-file'.
write
write
  • The built-in predicate ‘write’ outputs a term. So the goal

write( X)

    • will output the term X on the current output file, if X is instantiated;
    • if X is uninstantiated, a unique integer (_n) representing X is displayed.
    • succeeds only once, i.e. it fails on backtracking
  • X will be output in the same standard syntactic form in which Prolog normally displays values of variables.
  • A useful feature of Prolog is that the write procedure 'knows' to display a term no matter how complicated it may be.
  • additional built-in predicates for formatting the output:
    • tab(N) causes N spaces to be output.
    • nl (which has no argument) causes the start of a new line at output.
display x
display(X)
  • 'display' writes an expression showing operator precedence via prefix notation:

?- display(a+b*c*c),nl,write(a+b*c*c), nl.

+(a,*(*(b,c),c))

a+b*c*c

examples
Examples
  • Assume we have a procedure that computes the cube of a number:

cube(N,C) :- C is N * N * N.

Suppose we want to use this for calculating the cubes of a sequence of numbers. We can do this by a sequence of questions:

?- cube(2, X).

X = 8

?- cube(5, Y).

Y = 125

?- cube(12, Z).

Z = 1728

slide127
For each number, we had to type in the corresponding goal. Let's modify this program so that the cube procedure will read the data itself. It will read data until the atom ‘stop’ is read:
  • cube :- read(X),

process(X).

process(stop) :- !.

process(N) :- C is N * N * N,

write(C),

cube.

    • Note the indirect recursion above.
  • To run this program, we simply query with 'cube'.
  • This is a program whose declarative meaning is awkward to formulate.
  • However, its procedural meaning is straightforward:
    • to execute cube, first read X and then process it;
    • if X = stop then
    • everything has been done, otherwise
    • write the cube of X and recursively call the cube procedure to process further data
slide128
A table of the cubes of numbers can be produced using this new procedure as follows:

?- cube.

2. Note the .’s to terminate data input.

8

5.

125

12.

1728

stop.

yes

  • The numbers 2, 5 and 12 were typed in by the user on the terminal; the other numbers were output by the program. Note that each number entered by the user had to be followed by a full stop, which signals the end of a term.
prompts
Prompts
  • Our cube procedure could be modified as follows to include prompts:

cube :-

write(‘Next item, please:’),

read( X),

process(X ).

process(stop) :- !.

process(N) :-

C is N * N * N,

write(‘Cube of’),write(N),write(‘is’),

write(C), nl,

cube. /* Note again the indirect recursion! */

  • A conversation with this new version:

follows: Note .’s

?- cube.

Next item, please: 5.

Cube of 5 is 125

Next item, please: 12.

Cube of 5 is 125

Next item, please: stop.

yes

displaying lists
Displayinglists
  • Besides the standard Prolog format for lists, there are several other natural forms for displaying lists. The following procedure

writelist(L)

outputs a list L so that each element of L is written on a separate line:

writelist( [] ).

writelist([H | T]) :-

write(H), nl,

writelist(T).

displaying lists of lists
Displaying lists of lists
  • If we have a list of lists, one natural output form is to write the elements of each list in one line. To this end, we will define the procedure writelist2. An example of its use is:

?- writelist2([[a, b, c],[d, e, f],[g, h, i]]).

a b c

d e f

g h i

  • A procedure that accomplishes this is:

writelist2([]).

writelist2([L | LL]) :-

doline(L), nl,

writelist2(LL).

doline([]).

doline([H | T]) :-

write(H), tab(1),

doline(T).

bar graphs
Bar Graphs
  • A list of integer numbers can be sometimes conveniently shown as a bar graph. The following procedure, bars, will display a list in this form, assuming that the numbers in the list are between 0 and 80.
  • An example of using bars is:

?- bars([3, 4, 6, 5]).

***

****

******

*****

  • The bars procedure can be defined as follows:

bars([]).

bars([N | L]) :-

stars(N), nl,

bars(L).

stars(N) :-

N > 0,

write(*),

N1 is N - 1,

stars(N1).

stars(N) :-

N =< 0.

extra logicals
Extra-Logicals
  • These have a permanent effect on the environment / execution.
  • (A) Predicates affecting back-tracking
    • repeat
      • This allows an extra way of generating multiple solutions. It succeeds infinitely many times on backtracking.
      • e.g. get(X) could be roughly defined as follows:

get(X) :- new_get(X), X > 26.

(First 26 characters are non-printable)

new_get(X) :- repeat, get0(X).

get0 is made to succeed over and over again until X > 26.

      • It is possible to get the equivalent of an infinite loop via:

repeat,

…………….

…………….

…………….

fail,

……………..

……………..

etc

cut again
'cut' again
  • Cut (!)
    • stops backtracking. i.e. cuts the search space (search tree).
    • Very much dependent upon the order of execution. See earlier.

eg. of using ‘!’

      • a predicate to display the contents of a file

type (File) :- see(File), tell(user),

new_get(X), put(X), X = 26,!, seen. (26 = ^Z - eof)

    • The cut is needed so that once the EOF has been reached (26), backtracking never causes an attempt to read past end_of _file.
    • This is a very useful which allows you to quickly inspect a file while in a Prolog session via. e.g. 'type(a).'
b assert
(B) assert
  • These add and remove clauses from the database (i.e. current program).
  • assert
    • asserta(X) (where X is a rule or fact) adds the clause X at the beginning of the database
    • assertz(X) adds at the end of the database
  • Definition of ‘consult’:

consult(File) :-

seeing (Input), - save current input device

see (File),

repeat, - succeeds repeatedly forever

loop read (Term), - a clause

process (Term), - fails normally via

seen,

see(Input),! . - restore input device

process (Term) :- end_of_file_mark(Term), ! .

- not defined here

process(?-Q) :- call(Q), ! , fail. (See later for treatment of ‘fail’.)

/* call (Q) sets up Q as a query. */

process(Clause) :- assertz(Clause), fail.

(The last is the 'normal' case.)

c retract
(C) retract
  • retract
    • retract(X) enables a program to remove the first clause for X from the database

e.g.

retract(likes(john,apples))

will remove the first occurrence of the fact 'likes(john,apples)' from the database. Most likely this will be the only such occurrence.

retract(likes(_,_))

will remove the first of the 'likes' facts (whatever it is) from the database.

findall not to be used in assignments
findall(Not to be used in assignments)

(D) findall(Variable,<atom>,ListVariable)

  • Collects all the values from backtracking (many of which may not form part of the eventual solution) and puts them into a list. <atom> is a predicate with Variable as one of its variables.
  • ListVariable is bound to the list of values for Variable obtained by backtracking for those cases when the predicate succeeds.
collecting all solutions not to be used in assignments
Collecting All Solutions(Not to be used in assignments)
  • Prolog provides a mechanism for collecting all the solutions to a particular goal into a list
    • bagof (Ignore KG) - solutionsin the order they were produced, with duplicates
      • existential quantification (^) (Ignore KG)
      • will allow solutions to be gathered for all values of a term
    • setof - finds solutions in alphabetical order, without duplicates

bagof(X,plays(_,X),L).

bagof(X,Y^plays(Y,X),L).

setof(X,Y^plays(Y,X),L).

other built in predicates
Other Built-in Predicates
  • true, fail
    • true
      • always succeeds
    • fail
      • always fails
      • !, fail = “If execution proceeds to this point, abandon attempting to satisfy this goal:
  • Classifying terms
    • var(X)
      • succeeds of X is currently uninstantiated
    • nonvar(X)
      • succeeds of X is currently (not un)instantiated
      • e.g. nonvar(X) :- var(X), ! , fail.
    • atom(X)
      • succeeds if X stands for a Prolog atom
    • integer(X)
      • succeeds if X stands for an integer
    • atomic(X)
      • succeeds if X stands for either an atom or an integer
        • atomic(X) :- atom(X).

atomic(X) :- integer(X).

modeling in prolog

plays(jim,Sport) :- plays(ellen,Sport).

or

friend(jim,ellen).

plays(X,S) :- friend(X,Y), plays(Y,S).

Modeling in Prolog
  • need to identify what output (in general) we want out of the system
  • need to consider what information we need to input to be able to supply that output
  • need to represent the information in a way which will support the types of queries we will ask
  • The more general (and thus powerful) we want the system to be, the more sophisticated the rules need to be.

e.g. “Ellen finds a new friend, Jim, who will play every sport that she plays.”

  • Which of the two below is the better Model?
responses to prolog from a previous class
Responses to Prolog from a Previous Class
  • "I can't make [H|T] of it."
  • !, fail .