40
Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Embed Size (px)

Citation preview

Page 1: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Prolog

Harry R. Erwin, PhD

COMM2M

University of Sunderland

Page 2: 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 swi-prolog, available from sourceforge.org.

Page 3: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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

Page 4: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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(

Page 5: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 6: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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).

Page 7: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Compound Propositions

• Compound propositions have two or more atomic propositions, connected by logical operators.– Negation (¬) ¬a is “not a”

– Conjunction () a b is “a and b”

– Disjunction () ab is “a or b”

– Equivalence () ab is “a is equivalent to b”

– Implication () ab is “a implies b”

– Implication () ab is “a is implied by b”

Page 8: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.”

Page 9: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Clausal Forms

• All propositions can be restricted to ‘clausal’ form. This has the following general syntax:

B1B2 … BnA1A2…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.

Page 10: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Resolution

• An inference rule that generalizes the transitive relation: AB and BC implies AC

• 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.)

Page 11: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 12: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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’.

Page 13: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 14: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 15: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 16: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 17: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Assertions (headless Horn clauses)

female(shelley).

male(bill).

female(mary).

male(jake).

father(bill, jake).

father(bill, shelley).

mother(mary, jake).

mother(mary, shelley).

Page 18: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 19: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 20: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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’

Page 21: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Arithmetic

• Operates on integers (some systems handle reals, too.)

• Notation can be confusing. Consider:1. X is 2 + 3, X = 52. 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.

Page 22: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Comparisons

• Prolog compares integers arithmetically

• It compares all other constants as strings

Page 23: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Input/Output

• Interprets all symbols as sequences of characters forming their names.

Page 24: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 25: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Functor Names

• Rules are the same for all numbers of arguments.

• Integers can only be constants, not functors

• [] is only a constant.

Page 26: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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)

Page 27: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 28: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 29: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.[]

Page 30: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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 ‘_’.

Page 31: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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

Page 32: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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’.

Page 33: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 34: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 35: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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 ‘.’

Page 36: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 37: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

Some Standard Functions

consult(filename)

reconsult(filename)

fail

see(filename)

write(term)

tell(filename)

told

nl

atom(X)

var(X)

integer(X)

trace

notrace

Page 38: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

How do Procedure Calls Work?

• ‘unification’ is the magic word.

• We’ll work an example.

Page 39: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.

Page 40: Prolog Harry R. Erwin, PhD COMM2M University of Sunderland

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.