Prolog - University of Sunderland

Download Report

Transcript Prolog - University of Sunderland

Prolog
Harry R. Erwin, PhD
COMM2M
University of Sunderland
Primary Resources
• Kluzniak and Szpakowicz, Prolog for
Programmers, Academic Press, 1985.
• Pratt and Zelkowitz, Programming Languages,
Prentice-Hall, 3rd edition, 1996.
• Sebesta, Concepts of Programming Languages,
Addison-Wesley, 3rd edition, 1996.
• swi-prolog is available in M4 and on the upper
terraces.
• There are three versions of Prolog, including swiprolog, available from sourceforge.org.
Prolog Introduction
• A major language in the logic programming
category.
• Not a general-purpose language, instead it is
a tool for solving problems in predicate
calculus.
• Is applied to two different areas:
– Database queries
– Mathematical proofs
What is Prolog
• Prolog is a ‘descriptive’ rather than an
imperative programming language.
• The programmer need only specify ‘what’,
not how.
• It does have procedural elements.
• Non-standardized. 8(
History of Prolog
• Invented by Alain Coulmerauer and
Philippe Roussel, 1970-73.
• They needed a language for making
deductions from text.
• First working implementation in 1972 using
Algol.
• Specified by 1973.
• Several fairly similar versions exist.
Predicate Calculus and Prolog
• Proposition—logical statement that may or may
not be true. Consists of objects and relationships.
• Objects are simple terms, either constants or
variables. A variable can represent different
objects at different times.
• Atomic propositions consist of simple compound
terms, composed of a functor and an ordered list
of parameters.
• Propositions can be stated as truths (facts) or of
unknown validity (queries).
Compound Propositions
• Compound propositions have two or more atomic
propositions, connected by logical operators.
–
–
–
–
–
–
Negation
Conjunction
Disjunction
Equivalence
Implication
Implication
(¬)
()
()
()
()
()
¬a is “not a”
a b is “a and b”
ab is “a or b”
ab is “a is equivalent to b”
ab is “a implies b”
ab is “a is implied by b”
Variables
• Variables appear in propositions but only in
conjunction with quantifiers.
– Existential

•  X.P means “There exists a value of X such that P
is true”
– Universal

•  X.P means “For all X, P is true.”
Clausal Forms
• All propositions can be restricted to ‘clausal’ form.
This has the following general syntax:
B1B2  …  BnA1A2…Am
• I.e., this means if all of the As are true, at least one
B is true.
• Existential quantifiers are not needed.
• Universal quantifiers are implicit in the use of
variables.
• Only conjunction and disjunction are required.
Resolution
• An inference rule that generalizes the transitive
relation: AB and BC implies AC
• It works as follows: ‘and’ the left sides of both.
Then ‘and’ the right side of both. Delete the terms
present in both expressions. Toss in a ‘’ between
the left and right sides.
• The presence of variables in the propositions
requires values for those variables that allow this.
This process is called ‘unification’ and involves a
(long) search process with backtracking.
(Backtracking can be blocked in Prolog.)
Horn Clauses
• A restricted kind of clausal form, invented by A.
Horn.
• The types of propositions used in unification.
– Either have a single atomic proposition on the left side,
or none at all. The left side is called the ‘head’, and
those with a left side are called headed Horn clauses.
likes(bob,mary)likes(bob,redhead)redhead(mary)
– Headless Horn clauses are used to state facts.
father(bob,jake)
– Most (but not all) propositions can be stated as Horn
clauses.
How Prolog Works
• Prolog usually runs under an interpreter.
• The function consult reads new rules and
facts into a database.
• consult(user) allows the user to enter facts,
usually terminated by ctrl-D.
• writeit :- write(’Hello world’), nl.
• ‘writeit.’ then prints ‘Hello world’.
Overview
• Programs consist of:
– Facts
– Concrete relationships between facts
– A set of rules
• The user enters a query, a set of terms that all must
be made true. The facts and rules are then
consulted to determine the resulting values of the
variables. This magic is called ‘unification’.
• Programming in Prolog is like programming in
Lisp or ML.
Prolog Terms
• A constant, a variable, or a structure
• Constants are either atoms or integers.
• Atoms are strings of letters, digits, and
underscores beginning with a lowercase letter or a
string of printable ASCII characters delimited by
apostrophes.
• Variables are strings of letters, digits, and
underscores beginning with an uppercase letter.
These are unbound.
Variables
• When you bind a value (and thus a type) to
a variable is called instantiation. This occurs
during resolution.
• Instantiations last only long enough to
prove or disprove one proposition.
Structures
• Represent atomic propositions of the
predicate calculus.
• Have the format:
– functor(parameter list)
• The functor is an atom.
• The parameter list is a list of atoms,
variables, or other structures.
• Used to specify facts.
Assertions (headless Horn
clauses)
female(shelley).
male(bill).
female(mary).
male(jake).
father(bill, jake).
father(bill, shelley).
mother(mary, jake).
mother(mary, shelley).
Logical Propositions
• Based on headed Horn clauses (‘rules’).
• Can involve conjunctions (indicated by ‘,’)
• In Prolog, AND is implied.
female(shelley), child(shelley).
• Horn clauses are expressed as:
– consequence :- antecedent.
ancestor(mary, shelley) :- mother(mary, shelley).
• Consequences are single terms; antecedents can be
conjunctions.
Goals or Queries
• Appear identical to headless Horn clauses.
man(fred).
• The system responds ‘yes’ or ‘no’. Yes means the
system can prove it.
• Conjunctive propositions and propositions with
variables are also legal goals. When variables are
present, Prolog identifies the instantiations that
make the goal true.
• Interactive Prolog has two modes: one for entering
facts and rules, and the other for queries.
Data in Prolog
• Constant names are:
– A sequence of digits, possibly prefixed with ‘-’. These
are called integers.
– A string of letters, digits, and underscores, beginning
with a lower case letter, called identifiers.
– Symbols consisting of a non-empty sequence of ‘+ - * /
< = > . : ? $ & @ # \ ’
– Any one of ‘, ; !’
– [] (pronounced “nil”)
– Quoted strings: e.g, ‘string’
Arithmetic
• Operates on integers (some systems handle reals,
too.)
• Notation can be confusing. Consider:
1. X is 2 + 3, X = 5
2. X = 2 + 3, X = 5
• The Prolog operator ‘is’ means assign the
equivalent value, while the operator = means
assign the pattern. Clause 1 succeeds while clause
2 fails.
Comparisons
• Prolog compares integers arithmetically
• It compares all other constants as strings
Input/Output
• Interprets all symbols as sequences of
characters forming their names.
Compound Objects
• The type name is an integral part of all
occurrences of the object’s description.
• Define an object with its type, followed by a list of
its components:
– rectangle( 19, 24)
– timeofday( 19, 24)
• The type’s name is called a ‘functor’ and the
components are called ‘arguments’.
• The type attributes are its name and number of
arguments.
Functor Names
• Rules are the same for all numbers of
arguments.
• Integers can only be constants, not functors
• [] is only a constant.
Object Descriptions
• Descriptions of constants and compound objects
are ‘terms’. Sometimes the objects are also called
‘terms’.
• The arguments of a term are any terms.
• The outermost functor is the main or principal
functor
• Parentheses can be omitted using Polish notation
• A binary functor can be placed between its
arguments:
– a & b is equivalent to &(a, b)
Precedence
• Various standard functors (prefix, infix, and
postfix) are given priorities to eliminate
ambiguity if parentheses are omitted.
• These standard functors are called
operators.
• Operator names may not be quoted.
• Some functors (‘-’) are multiple types.
List Structures (similar to Lisp)
• Empty list is denoted ‘[]’
• Constructing functor is ./2 (. with two arguments,
hence infix)
• a cons b cons c cons emptylist becomes
– a.b.c.[]
• Don’t put whitespace immediately after ‘.’ That
has a syntactic meaning to Prolog
• Written [a, b, c, …]
• [A|B] means A is the list head and B the tail.
Strings
• Characters are constants of the same name.
Quoting a character is equivalent to writing
the character without the quotes.
• Strings are lists of characters. Write them in
double quotes.
• “string” is the same as s.t.r.i.n.g.[]
Variables
• Not the same as variables in normal programming
languages.
• A term denoting a variable is called a variable or
variable name.
• Has an unknown structure. If it ever becomes
defined, the variable becomes ‘instantiated’, and
ceases to be a variable.
• In terms of logic, a free or unbound variable has
become ‘bound’ to a term. If there are no variables
in the binding, it becomes ‘ground’.
• If want to refer to an arbitrary unnamed variable,
you can refer to it as ‘_’.
Term
• A set of objects
• Definition of a type
• Objects can satisfy explicit properties
– painting(Painter, ‘Saskia’)
• All ‘Saskia’s of an unknown artist
– painting(rembrandt, Picture)
• All pictures by Rembrandt
Prolog Operations
• Mostly user-defined procedures
• Standard or built-in operations are rarely
used.
• Every operation is written as a procedure
call.
– foo(bar(baz,quux), quuux(quuuux, qVux))
• foo is a ‘predicate symbol’ or ‘predicate’.
Procedure Calls
• Arguments may be both input and output.
– carcdr(Head.Tail, Head, Tail).
• The ‘stop’ or ‘.’ terminates the specification. In
this case, it defines the procedure.
• Call the procedure as follows:
– carcdr(1.2.3.[], H, T)
• This sets H to 1 and T to 2.3.[]
• The actual parameters of procedure calls are the
current instantiations of terms written in the call.
cons
• cons(Object, Another, Object.Another)
• Note that this is also the ‘definition’ of
carcdr. Which arguments are input or output
depends on the arguments, not the
definition! The meaning is defined by
context.
Prolog-10 (Edinburgh) Systems
• Versions of Prolog based on Prolog-10 function in
two modes:
– Command mode, where the system reads and executes
directives terminated by ‘.’
• Queries—one or more procedure calls separated by commas.
Used to ask questions of the system.
• Commands—queries prefixed by “:-”. Do not print.
– Definition mode, used to define procedures.
• Enter consult/1 or reconsult/1. The argument is a file name
with the procedure definitions, terminated by ‘.’
Comments
• Start with % and extend to the end of the
line.
• The expression ‘.%’ does not terminate a
clause and start a comment, so don’t do it.
Some Standard Functions
consult(filename)
reconsult(filename)
fail
see(filename)
write(term)
tell(filename)
told
nl
atom(X)
var(X)
integer(X)
trace
notrace
How do Procedure Calls Work?
• ‘unification’ is the magic word.
• We’ll work an example.
Prolog Deficiencies
• Efficiency reflects the ordering of pattern
matching during resolution. This can be
very slow.
• Infinite loops are easy to write.
f(X, Y) :- f(Z, Y), g(X, Z). (solution--reorder!)
• It assumes a closed world. If it isn’t in the
database, it’s false.
• Negation is very hard to handle.
Conclusions
• Prolog is a computer system for doing
mathematical logic. If, like me, you’ve studied this
field, you’ll find a lot of ideas familiar. (You also
may develop a case of schizophrenia like Goedel,
Price, or Nash. YMMV 8)
• It allows you to describe logical relationships and
deduce the implications.
• Treat it more like a powerful reasoning tool than a
traditional programming language.