prolog - computing science and mathematics, university of stirling · syntax 1. a prolog program...

63
Prolog John R. Woodward

Upload: others

Post on 13-Apr-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Prolog

John R. Woodward

PROgramming in LOGic.

1. Prolog is a logical and a declarative programming language.

2. The name itself, Prolog, is short for PROgramming in LOGic.

3. Prolog's heritage includes the research on theorem provers and other automated deduction systems (AI) developed in the 1960s and 1970s.

4. Sherlock Holmes deduced the criminal from facts.

5. There are only three basic constructs in Prolog: facts, rules, and queries.

To Start Prolog

To Load A file (database of facts)

Syntax

1. a Prolog program consists of a number of clauses, each ended with a fullstop ( . ).

2. Each clause is either a fact or a rule.

3. An atom is a group of alphanumeric characters starting with a small letter.

4. A variable is a group of alphanumeric characters starting with a capital letter.

5. Comments are enclosed by the delimiters /* and */. Or %

predicate

• a predicate is commonly understood to be a Boolean-valued function P: X→ {true, false},

• E.g. it is raining?

Simple Facts

• sunny.

• We can now ask a query of Prolog by asking

• ?- sunny.

• ?- is the Prolog prompt.

• Facts have some simple rules of syntax. Facts should always begin with a lowercase letter and end with a full stop.

Example facts.

• sunny. father(john, peter). father(john, mary). mother(susan, peter).

Examples of Simple Facts

1. Here are some simple facts about an imaginary world.

2. /* and */ are comment delimiters

3. john_is_cold. /* john is cold */

4. raining. /* it is raining */

5. john_Forgot_His_Raincoat. /* john forgot his raincoat */

We can interrogate this database

1. We can interrogate this database of facts, by again posing a query.

2. ?- john_Forgot_His_Raincoat.yes

3. ?- raining.

4. yes

5. ?- foggy.

6. no

Queries

1. A query is a predicate and its arguments, some of which are variables.

2. a valid query must have at least one fact in the knowledge base (database),

3. The purpose of submitting a query is to find values to substitute into the variables in the query such that the query is satisfied.

4. "what values will make my statement true".

Facts with Arguments

1. Relation names begin with a lowercase letter

2. likes(john,mary).

3. The above fact says that a relationship likes links john and mary.

4. It does not mean mary likes john.

5. You decide the convention

query

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

2. true.

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

4. false.

5. 4 ?- likes(john, Who). /* a capital letter */

6. Who = mary.

example

1. 5 ?- likes(Who,Who).

2. false.

3. %fails because the “Who”s need to be different

4. %means who likes him/her-self

5. 6 ?- likes(WhoX,WhoY).

6. WhoX = john,

7. WhoY = mary.

Variable Examples 2

• Instead of tapes you can think of CDs

• /*number, artist, album, favourite track*/

1. tape(1,van_morrison,astral_weeks,madam_george).

2. tape(2,beatles,sgt_pepper,a_day_in_the_life).

3. tape(3,beatles,abbey_road,something).

4. tape(4,rolling_stones,sticky_fingers,brown_sugar).

5. tape(5,eagles,hotel_california,new_kid_in_town).

Query ???

• ?- tape(5,Artist,Album,Fave_Song).

• ?- tape(4,rolling_stones,sticky_fingers,Song).

Query - answers

1. ?- tape(5,Artist,Album,Fave_Song). 2. /* what are the contents of tape 5 */ 3. Artist=eagles 4. Album=hotel_california 5. Fave_Song=new_kid_in_town 6. yes 7. ?- tape(4,rolling_stones,sticky_fingers,Song). 8. /* find just song */ 9. Song=brown_sugar 10. /* which you like best from the album */ 11. yes

Rules (fact with variables)

1. A rule can be viewed as an extension of a fact with added conditions that also have to be satisfied for it to be true.

2. It consists of two parts. 3. The first part is similar to a fact (a predicate with

arguments). 4. The second part consists of other clauses (facts

or rules which are separated by commas) which must all be true for the rule itself to be true.

5. These two parts are separated by ":-". You may interpret this operator as "if" in English.

Some facts

1. father(jack, susan). /* Fact 1 */

2. father(jack, ray). /* Fact 2 */

3. father(david, liza). /* Fact 3 */

Some Example Rules

parent(X, Y) :- father(X, Y). /* Rule 1 */ parent(X, Y) :- mother(X, Y). /* Rule 2 */ grandfather(X, Y) :- father(X, Z), parent(Z, Y).

/* Rule 3 */

question

• What is a grandfather.

• Given you have the rules father(X,Y) and parent

The Grandfather Rule

• grandfather(X, Y) :- father(X, Z), parent(Z, Y). /* Rule 3 */

• It means that "grandfather(X, Y)" is true if both "father(X, Z)" and "parent(Z, X)" are true.

• The comma between the two conditions can be considered as a logical-AND operator.

• parent(X, Y) :- father(X, Y). /* Rule 1 */ parent(X, Y) :- mother(X, Y). /* Rule 2 */

Rules 1 and 2 start with "parent(X, Y)".

• This means that "parent(X, Y)" is true when "father(X, Y)" is true, OR "mother(X, Y)" is true.

A list of father’s father’s, …

1. %facts about a family

2. parent(andy,bill).

3. parent(bill,clive).

4. parent(clive,dave).

5. parent(dave,evan).

6. %rule to determine ancestor

7. ancestor(X,Y) :- parent(X,Y).

8. ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y).

Illustrative queries

1 ?- ancestor(andy,evan).

• true .

• 2 ?- ancestor(evan,andy).

• false.

Common built-in predicates

• Arithmetic predicates (arithmetic operators): +, -, *, / (These operators are the same as those found in other programming languages. They only operates on numbers and variables.)

• Comparison predicates (comparison operators): • < (less than) - operates on numbers and variables only

• > (greater than) - operates on numbers and variables only

• =< (less than or equal to) - operates on numbers and variables only

• >= (greater than or equal to) - operates on numbers and variables only

• = - the two operands are identical

• =\= - the two operands do not have the same values

The process of deduction

• What is the Prolog interpreter doing deduction? 1. the facts and rules are loaded into the knowledge database. 2. When a query is given, Prolog searches the database from

top to bottom to find any facts or rules match with the query or goal.

3. If a match is found, the search for answers to the query succeeds and the goal is true. The values of any variables found are given.

4. If the user asks for further solutions (e.g by entering a semicolon in some Prolog interpreter), the Prolog interpreter continues searching. It keeps track of the facts and the rules which have been searched. When it can find no more solutions, it says no and the search ends.

Lists

[] This is an empty list.

[peter, 4, abc, X]

This is a list containing four elements. There is no restrictions on the number of variables and constants in the list.

[a, b, [c, d], e]

This list contains four elements. The third element is a list. This example shows that a list can also be an element of another list.

The head is the first element. The tail is the list

after the first element is removed.

List Head Tail

[] undefined undefined

[a] a []

[a, b] a [b]

[[a, b], c] [a, b] [c]

[[a, b], [c, d]] [a, b] [[c, d]]

Facts about head and tail

• head([H | T], H). /* R1 */

• tail([H | T], T). /* R2 */

• list([H | T], H, T). /* R3 */

Examples

1. head([a],a).

2. ?- head([a,b],a).

3. ?- tail([a,b],[b]).

4. ?- tail([a,b,c],[b,c]).

Examples

• head([a],a).

• true.

• ?- head([a,b],a).

• true.

• ?- tail([a,b],[b]).

• true.

• ?- tail([a,b,c],[b,c]).

• true.

Resolution

Suppose we have the following knowledge base:

• f(a).

• f(b).

• g(a).

• g(b).

• h(b).

• k(X) :- f(X), g(X), h(X).

The process is as follows:

1. Create a temporary variable _G34 (randomly-named) to stand in for Y. This is an implementation detail, so that if some other rule uses Y (a completely different variable), then the variable names don't collide.

2. The goal is to prove k(_G34). To do so, proving f(_G34), g(_G34), h(_G34) will be enough. This is the new goal.

3. To satisfy the first part of the new goal, f(_G34), the knowledge base is searched. There is no rule for f/1 (the predicate with arity one) but there is a fact: f(a). The first matching fact/rule is tried first. Thus, _G34 gets set to a(from unification).

4. Now, g(a), h(a) is the new goal. g(a) is satisfied just fine, because exactly that term is found in the knowledge base (trivial unification).

5. Now, h(a) is the new goal. But, nothing in the knowledge base unifies with h(a) and there is no h/1 rule, so there is a problem.

6. Go to the last decision point. This was when _G34 was set to a. Try to set it to something else. f(b) is in the knowledge base as well, so go with _G34 = b.

7. The new goal is g(b), h(b), etc… (which ultimately works).

To see this we can add print statements

f(a):- write("f(a)").

f(b):- write("f(b)").

g(a):- write("g(a)").

g(b):- write("g(b)").

h(b):- write("h(b)").

k(X) :- f(X), g(X), h(X).

And these are the outputs

f(a):- write("f(a)"). f(b):- write("f(b)"). g(a):- write("g(a)"). g(b):- write("g(b)"). h(b):- write("h(b)"). k(X) :- f(X), g(X), h(X). • ?- k(Y). • f(a)g(a)f(b)g(b)h(b) • Y = b.

PROgramming in LOGic –

PROLOG

Recursion, Lists & Predicates

CSCU9Y4

Recursion

• Recursion in Prolog means placing in the body of a rule a call to the predicate which occurs in the head of the rule.

• Here is a simple (bad) example:

stars :- write('*'), nl, stars.

• You should try this (give the goal ?- stars.).

• It doesn't work properly, and it is important to see why (and to see

what happens when you try it -- CTRL-C followed by 'a' will come in handy).

Recursion (2) • Recursion must always be made to terminate properly.

• Here is a better example: • stars(0) :- nl. • stars(N) :- write('*'), nl, M is N-1,

stars(M).

• And some others: • royal(victoria). • royal(X) :- parent(P,X), royal(P).

• archer(dan).

• archer(X) :- father(P,X), archer(P).

Lists

• The most important data structure in Prolog is the list.

• Actual lists are normally written out like this:

[3,7,5,29,6,3,1,2] [mary,john,bill,arthur]

[75]

[]

• But lists have alternative notations. •

[H|T] means the list with head H and tail T. [A,B|T] means the list whose first two members are A and B,

• with T as the rest of the list.

Lists (2)

• In the examples above:

– 3 is the head and [7,5,29,6,3,1,2] is the tail.

– mary is the head and [john,bill,arthur] is the tail.

– 75 is the head and [] is the tail.

•The empty list [] does not have a head and a tail.

•[2,1,3] [2|[1,3]] [2,1|[3]] [2|[1|[3|[]]]] all represent the same list.

Lists (3)

• Notes: – The tail of a list is a list.

– We must be careful to distinguish a one-member list from the object which is

its single member.

– Processing lists is almost always done using recursion.

– Task: to write out the members of a list, each on a separate line. writelist([]). writelist([H|T]) :-

write(H), nl,

writelist(T).

• This is the first illustration of the use of patterns in the head of a rule.

There are two cases here, represented by two rules, one for an empty list, and one for a list which is not empty. We shall see more of this, as it is significant.

Built-In List Operations

• Membership of a list: member(X,Y). Succeeds when X belongs to list Y.

• Length of a list: length(X,Y). 'Y is the length of list X'.

• Concatenate lists: append(X,Y,Z). 'Z is the result of concatenating lists X and Y.’

• Deleting from a list: delete(X,Y,Z). 'Z is the result of deleting all occurrences of Y from the list X.’

• Last in a list: last(X,Y). ‘X is the last member of list Y'.

Functions

• Prolog does not allow functions (methods, procedures …) .

• If we need to define a function to carry out certain computations, we can do so, but it must be done indirectly by means of a predicate. For example:

double(X,Y) :- Y is 2*X.

– Think of X and Y as parameters: X carries a value IN to the

operation of double, and Y carries a value OUT. – Example:

?- double(7,K).

– This will result in K being given the value 14.

Functions (2)

• Compute the larger of two numbers:

max(A,B,A) :- A >= B.

max(A,B,B) :- B > A.

• The first two parameters carry inputs, the third carries the output.

• Note that there is no explicit IF .. ELSE to distinguish the two cases.

Prolog will use the first rule if it can, otherwise it will use the second.

• Example goal: ?- max(4,7,M).

• This will result in M being given the value 7.

Functions (3) • Another:

sumlist([H|T],S) :- sumlist(T,N),

S is H+N.

sumlist([X],X).

• This predicate will compute (as the value given to the second parameter) the sum of the numbers in a list (the first parameter).

• Note the use of patterns for the IN parameter. The first clause deals with lists with one member only, the second deals with lists with more than one member.

• Example goal: ?- sumlist([6,2,5,2],V).

• This will result in V being given the value 15.

Functions (4)

• And patterns can be used for OUT parameters, too:

duplicate([],[]).

duplicate([H|T],[H,H|T1]) :-

duplicate(T,T1).

• This predicate will take a list (its first parameter), and duplicate

every member of it, to give a new list as the value of the second parameter.

• Example goal: ?- duplicate([6,2,5],E).

• This will result in E being given the value [6,6,2,2,5,5].

Structure of Programs

• How can a Prolog program be large and complex?

– Answer: rules for predicates can call other predicates.

• Schematically, here is a more complicated program: a :- b, c, d.

• b.

• c :- e, f.

• d :- g.

• e :- h.

• g.

• h.

Structure of Programs (2)

• A program is a collection of facts and rules. Normally there will be a

top level predicate --- the one which will form the goal which is given to the interpreter when we 'run the program'.

• It is standard practice to place the top-level predicate at the beginning of the program. In the above, a is the top-level predicate.

• Programs can be spread over a number of files without difficulty. Before being run, a program must be in the database. It is loaded by using consult, and we may consult several files if we need to.

Achieving Goals

• The interpreter is given a goal, it uses the first fact or rule in the database which matches the goal. – This matching may give values to variables.

• If a fact is used, the goal is achieved immediately.

• If a rule is used, the components of the body of the rule become subgoals, which are individually dealt with, in order. – Subgoals separated by commas must all be achieved. – Subgoals separated by semicolons are alternatives (if one fails then the next is tried).

• If any stage causes backtracking, the interpreter tries to find other ways to achieve goals.

Readability

• It is very easy to write programs which are correct but incomprehensible.

• Comments are essential in Prolog programs, and there should always be

comments to indicate, for each predicate, which other predicates call it.

• In the body of a rule, place the separate subgoals on separate lines.

• Use of blank lines, or of comment lines consisting of asterisks (say) can also help. Avoid clutter.

• Mixing up commas and semicolons in the body of a rule is a bad idea. It makes programs hard to follow, and you should avoid doing it if possible.

Example

• Recall parent(X,Y) :-

father(X,Y);mother(X,Y).

• Entirely equivalent to this is the following:

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

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

• I.e. two alternative rules.

• Frequently this can be done in preference to using a semicolon, and it makes programs much clearer.

term

structure

number

variable

atom

Formalities • Analysing the syntax of Prolog is useful to precisely

identify what constitutes a legal expression, i.e. an expression which the Prolog interpreter will understand.

• The syntax of Prolog is very simple, and may be expressed by the diagram:

Formalities (2)

• Every legal expression is a term.

• A term is either a constant, a variable, or a structure.

• A constant is either a number or an atom.

• Now we need only describe what numbers, atoms, variables and structures are.

Syntax • A number is just what you think.

– Integers and floating-point numbers

• An atom consists of characters in one of the following ways: – beginning with a lower-case letter (internal underscores

allowed). – alphanumeric, in particular combinations which are known to

the interpreter, e.g. :-, =, >=, etc. – Any string of characters enclosed in single quotes. If you need

to include a single quote in such an atom, put two single quotes, e.g.

'Bill''s House'

Syntax (2)

• A variable is an alphanumeric string which begins with an upper-

case letter or an underscore.

• A structure has a functor and arguments. The functor must be an atom, and the arguments can be Prolog terms of any kind. E.g.

child(mary,john)

date(29,2,96)

earlier(date(29,2,96),date(1,3,96))

• Every legal expression in Prolog which is not a number, an atom or a variable, is a structure with a functor and arguments.

Forms of Structures

• Some structures have alternative forms:

– Arithmetic expressions – Lists – Facts and rules

• Arithmetic expressions:

• 2 + 3 means +(2,3) • 2 < 3 means <(2,3) • 2 = 3 means =(2,3) • X is 2 + 3 means is(X,+(2,3))

Forms of Structures • Lists (the functor is always . )

• [H|T] means .(H,T) [2] means .(2,[]) [2,5,5] means .(2,.(5,.(5,[])))

•Facts and rules (the functor is always :- )

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

• is the same as :- (child(X,Y),parent(Y,X))

• age(anne,29).

• is the same as :- (age(anne,29),true)

Expressions in Prolog

• Prolog can read/write an entire term in one operation.

• There are no types in Prolog. Each variable can have as its value any Prolog term.

• Numbers and structures are different things. The goal • ?- 2 + 3 = 5. • will fail, because 2 + 3 is a structure, whereas 5 is a number.

• To evaluate an arithmetic expression we can use is:

?- X is 2 + 3, X = 5.

• will succeed.

• There is also =:=, which evaluates then tests equality: ?- 2 + 3 =:= 7 - 2.

• will succeed.

Data Structures

• Strictly, the only kind of expression which can represent structured data is the structure. There are no arrays or pointers. We do have lists, of course (which are a special kind of structure).

• Simple structures, e.g. father(dan,phil)

king(henry,8,england,1509,1547)

date(thursday,15,february,1996)

book('Algorithms','Sedgwick,R','Addison-Wesley',1988)

• These are structures which may be considered analogous to records. Such structures may be stored as facts, and data may be extracted by the use of goals containing variables:

?- king(henry,8,england,X,Y).

X = 1509

Y = 1547

Summary • What we’ve covered:

– logic and argument – goals and how to achieve them – facts and rules – the Prolog database – predicates and programs – use of variables – backtracking – recursion – data structures including lists – Prolog syntax

• Prolog is different - it’s a different paradigm

– the idea of program is totally unfamiliar – but some ideas persist from one paradigm to another