Lecture course: Heuristics & Prolog for Artificial Intelligence Applications Notes on Prolog from...

Post on 06-Jan-2018

235 views 2 download

description

Built-in predicate consult/1 consult/1 reads a program from file starting.pl into the database. Simplified form: ['/Users/bruce/prolog/starting.pl']. ?- consult(' /Users/bruce/prolog/starting.pl '). % relations compiled 0.00 sec, 0 bytes Yes ?-

Transcript of Lecture course: Heuristics & Prolog for Artificial Intelligence Applications Notes on Prolog from...

Lecture course: Heuristics & Prolog for Artificial

Intelligence Applications

Notes on Prolog

fromProfessor Bruce Batchelor, DSc.

E-mail: bruce@cs.cf.ac.uk

SWI-Prolog

Welcome to SWI-Prolog (Version 3.4.2)Copyright (c) 1990-2000 University of Amsterdam.Copy policy: GPL-2 (see www.gnu.org)

For help, use ?- help(Topic). or ?- apropos(Word).

?-

To start SWI-Prololg, type

swipl.

Prolog responds as shown below:

Built-in predicate consult/1

consult/1 reads a program from file starting.pl into the database.

Simplified form:['/Users/bruce/prolog/starting.pl'].

?- consult('/Users/bruce/prolog/starting.pl').% relations compiled 0.00 sec, 0 bytes

Yes?-

Operators

• Prolog has some pre-defined operators and the ability to define new ones. (We will look at the definition of operators later.)

• An operator is just a predicate for which a special abbreviated syntax is supported

The = operatorThe goal A = B succeeds if and only if A and B

can be unified:?- likes(mary,paul)= likes(mary,X).X = paulWe can also uselikes(mary,X), X = paulandX = paul, likes(mary,X)

SharingTwo uninstantiated variables can be shared

using the = operator. The following compound goal succeeds. Both X and Y are inastantiated to paul.

X = Y, likes(mary,X), likes(peter,Y)

Arithmetic Operators• Predicates +, -, *, / ,and ^ are arithmetic

operators, with the usual precedence and associativity.

• To evaluate an arithmetic expression use is not =.

?- Q is (2+3)*4.Q = 20 Yes

?- Q = (2+3)*4.Q = (2+3)*4 Yes

Lists in PrologProlog Comments[] Empty list

[a,b,c] Three elements

[a,2,3,5,b,7] Six elements

[a,[2,3,5],b,[7]] 4 elements. 2 sub-lists

[[]] 1 element (i.e. the empty list)

not([a,b,c] = [c,b,a]) List order is important

length(X,N) List X has N elements

[A|B] = [a,2,3,5,b,7] A = a. B = [2,3,5,b,7]

[a,[2,3,5],b,[7]] 4 elements. 2 sub-lists

Alternative List Notation

Usual List Notation Alternative Notation[] [][1] .(1,[])[1,2,3] .(1,.(2,.(3,[])))[1,likes(X,Y)] .(1,.(likes(X,Y),[]))

This topic is not examinable; it is included here merely to indicate how Prolog actually stores lists.

Heads, Tails & Pattern Matching

Prolog Comments[a|X] Head is a. Tail is X (X is a list)[A,B|X]= [a,b,c,d,e] A=a. B=b. X=[c,d,e] [_|b,c,d,e] Any list whose tail is [b,c,d,e][a|_] [a|X] Any list whose head is a[_] [X] Any list with 1 element[_,a,_] [X,a,Y] Any 3-elt. list whose 2nd elt. is a

List with 2 1-elt. sub-lists at front[[X],[Y]|Z]

Pattern matching is a powerful feature of Prolog and will be useful when we study Definite Clause Grammars for Natural Language Understanding.

Pretty Printer, pp/3

% Terminating clause pretty_print([]) :- nl.

% Recursive clause pretty_print([A|B]) :- tab(3), writenl(A), !, pretty_print(B).

Built-in Predicate member/2member(A,[A|_]).member(A,[_|B]) :- member(A,B).

member/2 is built-in and need not be defined by the user.Much of Prolog is defined in terms of Prolog. (E.g. not/1, repeat/0, append/3, etc.)If you can write member/2 from scratch, then you can program in Prolog!

Built-in Predicate append/3• append(X,Y,Z) succeeds if and only if Z is the

result of appending list Y onto the end of list X• The goal append([a,b,c],[d,e],Z) succeeds

with Z instantiated to [a,b,c,d,e] • Y = [a,b,c,d,e], append(X,[d,e],Y) succeeds with Y = [a, b, c, d, e] and X = [a, b, c]

• append/3 can be used with any pattern of instantiation (i.e. with variables in any positions)

Defining append/3append/3 is pre-defined but it can be defined in terms of "core" Prolog:% Terminating clause append([],A,A).

%Recursive clause append([H|Ta],B,[H|Tc]) :- append(Ta, B, Tc).

This definition is non-examinable and is included here merely to demonstrate the power of Prolog

More List PredicatesPredicate Descriptionmember(X,Y) Succeeds if list Y contains the element X.

cull(X,Y,Z) Instantiate Z to Y with all occurences of X deleted.

reverse(A,B) Instantiate B to list A with its elements written in reverse order

subset(A,B) Succeeds if all elements of A are also contained in Y.

Delete Defined Elements cull/3

cull(_,[],[]). %Terminating clause

cull(A,[A|B], C) :- % A is at head of the list!, % Cut - ignore this for the momentcull(A,B,C). % Now get to work on the tail

cull(A,[B|C], [B|D]) :- % A is not at head of the list!, % Cut - ignore this for the momentcull(A,C,D). % Again, work on the tail

List Reversal: reverse/2

This is not an efficient way to reverse a list!

% Terminating clause reverse([],[]).

%Recursive clause reverse([H|T],X) :- reverse(T,Y), append(Y,[H],X).

Cut (!)• Cut (!) is always satisfied when progressing forwards

through a program.• Cut does not allow back-tracking.• All instantiations are "frozen" when we pass cut.• Cut does not add anything to a program; no extra

solutions are available.• Cut can be useful to improve execution speed, by

eliminating unnecesary solutions.• Sometimes, it is possible to run a program using cut, when

it would be impossible without it.

Uses of Cut (!)

• Cut improves program speed.• Cut reduces memory requirments.• Prolog does not continue searching for

further solutions when one has been found.• Cut often makes it possible to improve the

range of a program e.g. fibonacci/2• Failure by negation.

Negation As Failure% What to do when X succeedsnot(X) :- call(X), !, fail.

% X did not succeed, so not(X)succeedsnot(_).

• To prove not(X), Prolog attempts to prove X• not(X) succeeds if X fails

Simple Queries

• A query asks Prolog to prove something• The answer is Yes or No (No = not proven)• Some queries (e.g. consult/1, write/1, nl/0) are executed

only for their side-effects. (E.g. write/1 always succeeds.)

?- likes(mary,paul).

Yes?- likes(mary,sue).

No?-

Final Period

• Queries can occupy several lines• If there is no final period, Prolog prompts for more input

by printing "|".

?- likes(paul,mary)| .

Yes?-

User typed "."

Queries With Variables

• Term with variables can appear as a query.• Prolog shows the bindings necessary to prove the query.

(In this case, P = john.)

?- likes(mary,Q).

P = john

Yes?- likes(paul,nelly).

No

Prolog waits here for input. Press RETURN to proceed.

Flexibility

Variables can appear in any position:– ?- likes(mary,john). – ?- likes(mary,W).– ?- likes(X,john).– ?- likes(Y,Z).

If we run the last query, hitting semi-colon (;) instead of RETURN, we obtain multiple solutions.

Synonyms

• Equivalent ways of saying the same thing– Goal satisfaction– Theorem proving– Satisfying a query

• Note: We do not refer to executing, or running, a Prolog program, as there are no instructions.

Stopping Goal Satisfaction

• Click CTRL/D to terminate goal satisfaction. Usefule when a program is seemingly stuck in an infinite loop.

• Warning: Clicking CTRL/D again, in response to the prompt (?-), terminates SWI-Prolog and returns control to the UNIX shell.

Compound Goals / Conjunctions

• A compound goal has a list of query terms (sub-goals), separated by commas

• Prolog tries prove them all, using a single set of bindings.

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

Yes

Conjunctions - 2

• A conjunctive query has a list of query terms separated by commas

• Prolog tries prove them all, using a single set of bindings.• X is instantiated during satisfactionof this goal.

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

X = paul ;

No

Multiple Solutions

• Here, there is more than one solution (i.e.way to prove the query)

• Typing ; rather than RETURN, asks Prolog to find more solutions.

• X is repeatedly instantiated / uninstantiated here.

?- likes(mary,X).X = john ;X = paul ;X = bonzo ;X = kissing ;No?-

Back-trackingConsider the compound goalgo :-likes(mary,X),write(X),nl,likes(X,mary).X is initially instantiated to john. (First sub-goal)Prolog prints X (john) then tries to prove thatlikes(john,mary)

is true. However, there is no such clause. So, Prolog then back-tracks to the first sub-goal and then tries to find another solution. One is found requiring that X be instantiated to paul. This value is then printed. Finally,

likes(paul,mary)is proved true, so go/0 succeeds.

Rules

friends(A, B) :- likes(A, B), likes(B, A).

Head

Read as "can be proved to be true if" or more simply "if".

Conjunction. AND sub-goals.

Two sub-goals form the body of the rule

Rules

• To prove the head of a rule, satisfy each of its sub-goals

• To prove friends(A,B), find some A and B for which you can prove likes(A,B), then likes(B,A)

Programs With Rules

female/1 consists of 6 clauses (i.e. a fact or a rule), ending with a period.

male(albert). male(henry). male(john).male(paul). male(peter).% Factsfemale(mary). female(florence).female(mary). female(sue).% Rulesfemale(A) :- likes(A,_), not(male(A)).female(A) :- likes(_,A), not(male(A)).

Rules Using Other Rules

opposite_sex(A,B) :- male(A),female(B).

opposite_sex(A,B) :-female(A),male(B).

female/1 is defined in terms of male/1 and likes/2. (not/1 is a built-in predicate.)

Another example Notice the hierarchical structure of the program.

Rules: Scope of Variables

The scope of a variable is local to the clause that contains it

opposite_sex(A,B) :- male(A),female(B).

opposite_sex(C,D) :-female(C),male(D).

A and B have no relevance to second clause

Following definition has the same effect as in the previous example, despite the change of variable names.

Recursive Rules

X is an ancestor of Y if:(i) X is a parent of Y (Terminating clause) OR(ii) There is some Z such that Z is a parent of Y

AND X is an ancestor of Z

% Terminating clause ancestor(X,Y) :- parent(X,Y).

% Recursive clauseancestor(X,Y) :-

parent(Z,Y), ancestor(X,Z).

Recursive RulesSome predicates may have several

clauses, which may be facts or rules.

Prolog tries to prove the query using clauses in the order they appear in the program, so it is usual to put terminating rules / facts first.