6
BIRLA INSTITUTE OF TECHNOLOGY AND SCIENCE Second Semester 2007-2008 EA C461 Artificial Intelligence Lab 1: Introduction to PROLOG and WinProlog Document Prepared By: Mukesh Kumar Rohil, CS & IS Group BITS, Pilani – 333031 (Rajasthan), India [email protected] PROLOG (PROgramming in LOGic) is the programming language chosen as the basis for the new generation of computers systems, by Japan. Based on mathematical logic, it enables the programmer to concentrate on the declarative, non-procedural aspect of programming. This is the main feature, which distinguishes PROLOG from other programming languages, thus representing a step in the development of automatic programming tools. Mathematical or symbolic logic deals with rules of logical reasoning, i.e. rules of inferring conclusions from given statements (axioms). Most of the high-level programming languages (like Basic, Pascal, C, COBOL or FORTRAN) are not based on the principles of mathematic logic. These languages enables us to use the computer as an effective tool for quick and precise computing and can serve as ‘reliable assistant’ that is capable of dealing with a large amount of systematically organized data and can always efficiently find the desired information. The new trend in computer science is to enable computers to handle more difficult tasks such as, for example, the simulation of experts’ reasoning. Computer scientists have already developed many successful applications of expert systems that can intelligently solve problems in various domains. Expert systems can perform intelligent reasoning and can explain how they derive their conclusions. The standard programming languages can be used to program expert systems, but obviously languages based on the principle of mathematical logic are much more appropriate for this task. The most useful language of so-called logic programming is PROLOG. Prolog is introduced through formal logic. For practical programming in Prolog such formal introduction of formal logic is not necessary. It is sufficient to state that Prolog is based on the first order predicate calculus restricted to Horn clauses that have the following form: If condition1 and condition2 and ... conditionN are satisfied then conclusion is true. More precisely, Prolog clauses are extensions of Horn clauses, since Prolog also allows negative (negated) conditions. A Horn clause translated to Prolog syntax gives us the following Prolog clauses: conclusion :- condition1, condition2, . . . conditionN. In Prolog, such a clause is called a rule. A clause without conditions is called a fact. A Prolog program consists of a set of facts and rules that describe objects and relations between objects in a given domain. Facts are statements that are always unconditionally true, while rules declare properties and relations that are true depending on given conditions. A Sample Prolog Program Consider the following family tree: --> peter mary --> ann -->| --> jane Here is the corresponding Prolog program: child(ann, mary). % ann is mary’s child child(peter, ann). child(jane, ann). parent(X, Y) :- /* X is parent of Y */ child(Y, X). The program consists of four clauses- three facts and one rule-each terminated by a period. The facts describe the family relations. The fourth clause is a rule stating that ‘for all X and Y, X is a parent of Y if Y is a child of X. 1

Lab 1 Introduction to PROLOG

Embed Size (px)

Citation preview

Page 1: Lab 1 Introduction to PROLOG

BIRLA INSTITUTE OF TECHNOLOGY AND SCIENCESecond Semester 2007-2008EA C461 Artificial Intelligence

Lab 1: Introduction to PROLOG and WinProlog

Document Prepared By: Mukesh Kumar Rohil, CS & IS Group BITS, Pilani – 333031 (Rajasthan), India [email protected]

PROLOG (PROgramming in LOGic) is the programming language chosen as the basis for the new generation of computers systems, by Japan. Based on mathematical logic, it enables the programmer to concentrate on the declarative, non-procedural aspect of programming. This is the main feature, which distinguishes PROLOG from other programming languages, thus representing a step in the development of automatic programming tools.

Mathematical or symbolic logic deals with rules of logical reasoning, i.e. rules of inferring conclusions from given statements (axioms). Most of the high-level programming languages (like Basic, Pascal, C, COBOL or FORTRAN) are not based on the principles of mathematic logic. These languages enables us to use the computer as an effective tool for quick and precise computing and can serve as ‘reliable assistant’ that is capable of dealing with a large amount of systematically organized data and can always efficiently find the desired information.

The new trend in computer science is to enable computers to handle more difficult tasks such as, for example, the simulation of experts’ reasoning. Computer scientists have already developed many successful applications of expert systems that can intelligently solve problems in various domains. Expert systems can perform intelligent reasoning and can explain how they derive their conclusions. The standard programming languages can be used to program expert systems, but obviously languages based on the principle of mathematical logic are much more appropriate for this task.

The most useful language of so-called logic programming is PROLOG. Prolog is introduced through formal logic. For practical programming in Prolog such formal introduction of formal logic is not necessary. It is sufficient to state that Prolog is based on the first order predicate calculus restricted to Horn clauses that have the following form:

If condition1 and condition2 and ... conditionN are satisfied then conclusion is true.

More precisely, Prolog clauses are extensions of Horn clauses, since Prolog also allows negative (negated) conditions. A Horn clause translated to Prolog syntax gives us the following Prolog clauses:

conclusion :- condition1,condition2, . .

. conditionN.

In Prolog, such a clause is called a rule. A clause without conditions is called a fact. A Prolog program consists of a set of facts and rules that describe objects and relations between objects in a given domain. Facts are statements that are always unconditionally true, while rules declare properties and relations that are true depending on given conditions.

A Sample Prolog Program

Consider the following family tree:

--> petermary --> ann -->| --> jane

Here is the corresponding Prolog program:

child(ann, mary). % ann is mary’s child child(peter, ann).child(jane, ann).

parent(X, Y) :- /* X is parent of Y */child(Y, X).

The program consists of four clauses- three facts and one rule-each terminated by a period. The facts describe the family relations. The fourth clause is a rule stating that ‘for all X and Y, X is a parent of Y if Y is a child of X.

According to the Prolog syntax, names of relationships and objects are written with lowercase initials while uppercase initials are used for variables (X and Y in the fourth clause). In this program, names are constants as each name denotes exactly one person (one particular individual object). Variables in the program denote any person (any object) for whom the relation defined in the program is satisfied.

A program must first be typed in, using some text editor, making sure that

each clause terminates with a period, There is no blank space between a name of the

relation and the left bracket of the arguments, (i.e. parent (X, Y) is wrong, while parent(X,Y) is correct syntax)

There is a space before and after the symbol ‘:-‘, and

The correct type of letter is used in names.

In WinProlog we have standard menu for File, Edit, Run (compile and run) at the top. You can use these facilities for typing your program, saving, compiling and running goals, if you prefer.

After the program has been stored on a file, e.g. named ‘exercise.pl’, we can run the Prolog compiler or interpreter. This can be done by, double clicking the mouse button at the icon if you are using WinProlog for Windows or issuing the command ‘prolog’ to MS-DOS prompt if you are using Turbo Prolog. We will not discuss Turbo Prolog here, because it deviates from the standard Prolog in many ways and does not truely

1

Page 2: Lab 1 Introduction to PROLOG

implements Edinburg’s syntax. Turbo Prolog programmers, has many other things to add to the programs. These are domains, predicates, clauses, database, goal etc. using some different syntax. For know how of Turbo Prolog readers are suggested to concern users guide for Turbo Prolog. Here onwards we will not discuss about Turbo Prolog.

The Prolog interpreter or compiler (as there are few Prolog systems which can be set as interpreter or compiler based on user’s choice), is ready when the following Prolog prompt is displayed in console window:

?-

Now Prolog is ready to execute our commands. Our first command is to read in the program file ‘exercise.pl’. This can be achieved by typing the command ‘consult(‘Filename’)’.

?- consult(‘exercise.pl’).

Note that there is no blank between ‘consult’ and the bracket ‘(‘ and that the command is terminated with a period. If Prolog finds any syntax errors in the program whilst reading it in, the compiler informs us the errors.

We may exit by typing the appropriate command, in the console window.

?- halt.

If there are no syntax errors in the program the compiler answers ‘yes’ and is now ready for execution.Now issue the following commands one after another and inspect the output after each command.

?- listing.

?- child(ann, mary).

?- child(ann, jane).

?- child(X, mary).

?- child(peter, X).

?- child(X, Y).

?- parent(X, ann).

Prolog as a Step Towards Automatic Programming

The sample program partially demonstrates two important features. First, programming in Prolog consists of describing relations between objects and not prescribing how the system should solve a task by a fixed sequence of instructions. And second, there is no distinction between data and program, between data retrieval and computation. In each case we determine one or more arguments of a relation using the relations given by the program.

In these aspects, Prolog is substantially different from procedural languages like C, ForTran or Pascal. When programming in these languages, a programmer’s task

is to translate a problem from its natural language specification – what is to be done (the declaration of the problem) – into a sequence of commands of a certain programming language that determines how to solve the given problem (proceduralization of the problem). In Prolog, the programmer’s task is to translate the program from its natural language specification into its formal logic form. A Prolog program thus determines what is to be done without saying how. A logical interpretation of a Prolog program is the following:

Prolog accepts a set of facts and rules as a set of axioms and user’s questions as a theorem;

It then tries to verify the theorem by logically deriving it from the set of axioms.

A further illustration of the above features is in the program below which computes the greatest common divisor of two numbers, using the Euclid’s algorithm.In C, the solution of the problem is the following:

int divisor(int A, int B) { while (A != B) if ( A > B) A = A – B; else B = B – A; return A; }

In Prolog, the program is in fact a definition of the relation ‘divisor’. It has three arguments and is satisfied if the third argument is the greatest common divisor of the first two.

divisor(A, A, A).divisor(A, B, Divisor) :-

A > B,A1 is A – B,divisor(A1, B, Divisor).

divisor(A, B, Divisor) :-B > A,B1 is B – A,divisor(B1, A, Divisor).

A programmer familiar to programming in procedural languages will wonder how describing relations between objects enables the computer to infer some solution or to perform a certain computation using Prolog. In Prolog, the control mechanism, which executes inferences, is a part of the Prolog interpreter or compiler itself. Thus, given the necessary facts and rules, Prolog uses built-in deductive reasoning mechanism to solve the problems. In this way, Prolog represents a step towards automatic programming, whose goal is to enable the programmer to state only the specifications of the problem and what is to be computed.

Try the following goals one after other and note the output after each goal

?- X =.. [child, ann, jane].

?- X =.. [name, billy, kid], Y =.. [profession, thief], Z =.. [gunman, X, Y].

2

Page 3: Lab 1 Introduction to PROLOG

?- beatles([john, paul, george, ringo]) =.. X.

The operator ‘=..’ (univ operator) is a built-in predicate (or procedure) which can be used for constructing arbitrary Prolog structure. It can be used in both directions: to construct a structure from a list and to construct a list from a structure.

Try the following Prolog program which tests whether list1 is longer than list2

% longer(List1, List2)longer([_|_], []).longer([_|TailOfFirst], [_|TailOfSecond]) :- longer(TailOfFirst, TailOfSecond).

Try the following program which finds the number of elements in a list

length([], 0).length([_|Tail], N) :-

length(Tail, LenTail),N is LenTail + 1.

PROLOG (Some Tips) Prolog programs can be extended, by simply

adding new clauses. Even at run-time! Prolog clauses are of three types: facts, rules

and questions. Facts declare things that are always,

unconditionally true. Rules declare things that are true depending

on a given condition. By means of questions the user can ask the

program what things are true. Prolog clauses consist of the head and the

body. The body has a list of goals separated by commas. Commas are understood as conjunctions.

Facts are the clauses that have the empty body. Questions only have the body. Rules have the head and the (non-empty) body.

In the course of computation, a variable can be substituted by another object. We say that a variable becomes instantiated.

All variables are assumed as universally quantified and are read as ‘for all’. Alternative readings are, however, possible for variables that appear only in the body. For example,

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

can be read in two ways:

(a) For all X and Y, if X is a parent of Y then X has a child.

(b) For all X, X has a child if there is some Y such that X is a parent of Y.

Simple objects in Prolog are atoms, variables and numbers. Structured objects, or structures, are used to represent objects that have several components.

Structures are constructed by means of functors. Each functor is defined by its name and arity (number of arguments).

The type of object is recognized entirely by its syntactic form.

The lexical scope of variables is one clause. Thus the same variable name in two clauses means two different variables.

Structures can be naturally pictured as trees. Prolog can be viewed as a language for processing trees.

The matching operation takes two terms and tries to make them identical by instantiating the variables in both terms.

Matching, if it succeeds, results in the most general instantiation of variables.

The declarative semantics of Prolog defines whether a goal is true with respect to a given program, and if it is true, for what instantiation of variables it is true.

A comma between goals means the conjunction of goals. A semi-colon between goals means disjunction of goals.

The procedural semantics of Prolog is a procedure for satisfying a list of goals in the context of a given program. The procedure outputs the truth or falsity of the goal list and the corresponding instantiation of variables. The procedure automatically backtracks to examine alternatives.

The declarative meaning of programs in ‘pure Prolog’ does not depend on the order of clauses and the order of goals in the clauses.

The procedural meaning does depend on the order of goals and clauses. Thus the order can affect the efficiency of the program; an unsuitable order may even lead to infinite recursive calls.

Given a declaratively correct program, changing the order of clauses and goals can improve the program’s efficiency while retaining its declarative correctness. Reordering is one method of preventing infinite looping.

There are other more general techniques, apart from reordering, to prevent indefinite looping and thereby make programs procedurally robust.

Prolog programming consists of defining relations and querying about relations.

A prolog program consists of clauses. These are of three types: facts, rules and questions.

A relation can be specified by facts, simply stating the n-tuples of objects that satisfy the relation, or by stating rules about the relation.

A procedure is a set of clauses about the same relation.

Querying about relations, by means of questions, resembles querying a database. Prolog’s answer to a question consists of a set of objects that satisfy the question.

In Prolog, to establish whether an object satisfies a query is often a complicated process that involves logical inference, exploring among alternatives and possibly backtracking. All this is done automatically by the Prolog system and is, in principle, hidden from the user.

Two types of meaning of Prolog programs are distinguished: declarative and procedural. The

3

Page 4: Lab 1 Introduction to PROLOG

declarative view is advantageous from the programming point of view. Nevertheless, the procedural details often have to be considered by the programmer as well.

A trial version of Developer’s Edition of WinProlog compiler can be downloaded freely from http://www.lpa.co.uk

Please find below some WinProlog programs, taken from examples folder (directory) of WinProlog.

/* Example File: Eg_gfx.pl A Simple Graphics Demo Dave Westwood and Brian D Steel=================================The gfx_eg/0 predicate runs a demonstration graphics example which displays a dialog containing a "Grafix" window filled with a rectangle and an ellipse. The example shows how a paint message is handled so as to refresh only the portion of the window that needs repaint.*/

% create the dialog, set its handler and then show the dialog

gfx_eg :- create_gfx_eg, window_handler( gfx_eg, gfx_eg_handler ), show_dialog( gfx_eg ).

% create the grafix example dialog windows

create_gfx_eg :- wdcreate( gfx_eg, `Graphics Example`, 240, 83, 146,197, [ws_sysmenu, ws_caption] ), wccreate( (gfx_eg,900), grafix, `Grafix`, 16, 16, 112, 96, [ws_child, ws_border, ws_visible] ), wccreate( (gfx_eg,1), button, `Ok`, 32, 128, 80, 32, [ws_child, ws_visible, ws_tabstop, bs_pushbutton] ).

% close message is handled by atom "close"

gfx_eg_handler( _, msg_close, _, close ).

% handle the "ok" button by returning the atom "ok"

gfx_eg_handler((gfx_eg,1), msg_button, _,ok).

% handle paint messages by starting, drawing some graphics, and ending

gfx_eg_handler( Win, msg_paint, grafix, _ ) :- gfx_paint( Win ), gfx( ( rectangle( 10, 10, 100, 80 ), ( brush = stock(gray_brush) -> ellipse( 10, 10, 100, 80 ) ) ) ), gfx_end( Win ).

/* Example file: mci.plMCI Functions for WIN-PROLOG - Brian D Steel =========================================The mci/1 and mci/2 predicate are used to send command strings to the WINMM.DLL (Windows MultiMedia) API, and permits supported files to be played under Prolog control. For example: ?- mci( `play \windows\tada.wav` ).plays the Windows "TADA" sound file, TADA.WAV, while: ?- mci( `play d:\videos\pcmag.avi`, Result ).displays and runs the "PCMAG" video file, and returns the result. Assuming that the files are available at the specified locations*/

% perform the given MCI command and check the result

mci( Command ) :- catch( Error, mci(Command,(Return,_)) ), !, throw( Error, mci(Command) ), ( Return = 0 -> true ; Return = -1 -> fail ; Code is Return + 10000, throw( Code, mci(Command) ) ).

% perform given MCI command and return result

mci( Command, Result ) :- fcreate( mci, [], -2, 256, 0 ), catch( Error, winapi((winmm,mciSendStringA),[Command,mci,256,0],0,Return) ), !, wintxt( mci, 0, 0, String ), fclose( mci ), throw( Error, mci(Command,Result) ), Result = (Return,String).

Bibliography

1. Bratko Ivan, “Prolog Programming for Artificial Intelligence”, Indian Reprint, Pearsoned Education2. Burnhan, W D , Hall A R, “Prolog Programming and Applications”, Macmillan Education Ltd.3. Clocksin W F, Mellish C S, “Programming in Prolog”, Narosa Publisjing House, New Delhi4. Sterling L, Shapiro L, “The Art of Prolog – Advanced Programming Techniques”, MIT Press5. I Kononenko and N Lavrac, “Prolog Through Example: A practical programming guide”, Galgotia Publications (Pvt) Ltd6. P Ross, “Advanced Prolog”, Addison-Wesley7. N Ford, “Prolog Programming”, John Wiley

4