You are on page 1of 4

BIRLA INSTITUTE OF TECHNOLOGY AND SCIENCE .

Second Semester 2007-2008 conditionN.


EA C461 Artificial Intelligence
In Prolog, such a clause is called a rule. A clause
Lab 1: Introduction to PROLOG and WinProlog without conditions is called a fact. A Prolog program
consists of a set of facts and rules that describe objects
Document Prepared By: and relations between objects in a given domain. Facts
Mukesh Kumar Rohil, CS & IS Group BITS, are statements that are always unconditionally true,
Pilani – 333031 (Rajasthan), India while rules declare properties and relations that are
rohil@bits-pilani.ac.in true depending on given conditions.

PROLOG (PROgramming in LOGic) is the programming A Sample Prolog Program


language chosen as the basis for the new generation of
computers systems, by Japan. Based on mathematical Consider the following family tree:
logic, it enables the programmer to concentrate on the
declarative, non-procedural aspect of programming. --> peter
This is the main feature, which distinguishes PROLOG mary --> ann -->|
from other programming languages, thus representing --> jane
a step in the development of automatic programming
tools. Here is the corresponding Prolog program:

Mathematical or symbolic logic deals with rules of child(ann, mary). % ann is mary’s child
logical reasoning, i.e. rules of inferring conclusions child(peter, ann).
from given statements (axioms). Most of the high-level child(jane, ann).
programming languages (like Basic, Pascal, C, COBOL
or FORTRAN) are not based on the principles of parent(X, Y) :- /* X is parent of Y */
mathematic logic. These languages enables us to use child(Y, X).
the computer as an effective tool for quick and precise
computing and can serve as ‘reliable assistant’ that is The program consists of four clauses- three facts and
capable of dealing with a large amount of one rule-each terminated by a period. The facts
systematically organized data and can always describe the family relations. The fourth clause is a rule
efficiently find the desired information. stating that ‘for all X and Y, X is a parent of Y if Y is a
child of X.
The new trend in computer science is to enable
computers to handle more difficult tasks such as, for According to the Prolog syntax, names of relationships
example, the simulation of experts’ reasoning. and objects are written with lowercase initials while
Computer scientists have already developed many uppercase initials are used for variables (X and Y in the
successful applications of expert systems that can fourth clause). In this program, names are constants as
intelligently solve problems in various domains. Expert each name denotes exactly one person (one particular
systems can perform intelligent reasoning and can individual object). Variables in the program denote any
explain how they derive their conclusions. The person (any object) for whom the relation defined in
standard programming languages can be used to the program is satisfied.
program expert systems, but obviously languages
based on the principle of mathematical logic are much A program must first be typed in, using some text
more appropriate for this task. editor, making sure that
• each clause terminates with a period,
The most useful language of so-called logic • There is no blank space between a name of the
programming is PROLOG. Prolog is introduced through relation and the left bracket of the arguments,
formal logic. For practical programming in Prolog such (i.e. parent (X, Y) is wrong, while parent(X,Y) is
formal introduction of formal logic is not necessary. It correct syntax)
is sufficient to state that Prolog is based on the first • There is a space before and after the symbol
order predicate calculus restricted to Horn clauses that ‘:-‘, and
have the following form: • The correct type of letter is used in names.
If condition1 and condition2 and ... conditionN are In WinProlog we have standard menu for File, Edit, Run
satisfied then conclusion is true. (compile and run) at the top. You can use these
facilities for typing your program, saving, compiling
More precisely, Prolog clauses are extensions of Horn and running goals, if you prefer.
clauses, since Prolog also allows negative (negated)
conditions. A Horn clause translated to Prolog syntax After the program has been stored on a file, e.g.
gives us the following Prolog clauses: named ‘exercise.pl’, we can run the Prolog compiler or
interpreter. This can be done by, double clicking the
conclusion :- mouse button at the icon if you are using WinProlog for
condition1, Windows or issuing the command ‘prolog’ to MS-DOS
condition2, prompt if you are using Turbo Prolog. We will not
. discuss Turbo Prolog here, because it deviates from the
.

1
standard Prolog in many ways and does not truely programming in these languages, a programmer’s task
implements Edinburg’s syntax. Turbo Prolog is to translate a problem from its natural language
programmers, has many other things to add to the specification – what is to be done (the declaration of
programs. These are domains, predicates, clauses, the problem) – into a sequence of commands of a
database, goal etc. using some different syntax. For certain programming language that determines how to
know how of Turbo Prolog readers are suggested to solve the given problem (proceduralization of the
concern users guide for Turbo Prolog. Here onwards we problem). In Prolog, the programmer’s task is to
will not discuss about Turbo Prolog. translate the program from its natural language
specification into its formal logic form. A Prolog
The Prolog interpreter or compiler (as there are few program thus determines what is to be done without
Prolog systems which can be set as interpreter or saying how. A logical interpretation of a Prolog
compiler based on user’s choice), is ready when the program is the following:
following Prolog prompt is displayed in console window: • 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.
Now Prolog is ready to execute our commands. Our
first command is to read in the program file A further illustration of the above features is in the
‘exercise.pl’. This can be achieved by typing the program below which computes the greatest common
command ‘consult(‘Filename’)’. divisor of two numbers, using the Euclid’s algorithm.
In C, the solution of the problem is the following:
?- consult(‘exercise.pl’). int divisor(int A, int B)
{
Note that there is no blank between ‘consult’ and the while (A != B)
bracket ‘(‘ and that the command is terminated with a if ( A > B)
period. If Prolog finds any syntax errors in the program A = A – B;
whilst reading it in, the compiler informs us the errors. else
B = B – A;
We may exit by typing the appropriate command, in return A;
the console window. }

?- halt. In Prolog, the program is in fact a definition of the


relation ‘divisor’. It has three arguments and is
If there are no syntax errors in the program the satisfied if the third argument is the greatest common
compiler answers ‘yes’ and is now ready for execution. divisor of the first two.
Now issue the following commands one after another
and inspect the output after each command. divisor(A, A, A).
divisor(A, B, Divisor) :-
?- listing. A > B,
A1 is A – B,
?- child(ann, mary). divisor(A1, B, Divisor).
divisor(A, B, Divisor) :-
?- child(ann, jane). B > A,
B1 is B – A,
?- child(X, mary). divisor(B1, A, Divisor).

?- child(peter, X). A programmer familiar to programming in procedural


languages will wonder how describing relations
?- child(X, Y). between objects enables the computer to infer some
solution or to perform a certain computation using
?- parent(X, ann). Prolog. In Prolog, the control mechanism, which
executes inferences, is a part of the Prolog interpreter
Prolog as a Step Towards Automatic or compiler itself. Thus, given the necessary facts and
Programming rules, Prolog uses built-in deductive reasoning
mechanism to solve the problems. In this way, Prolog
The sample program partially demonstrates two represents a step towards automatic programming,
important features. First, programming in Prolog whose goal is to enable the programmer to state only
consists of describing relations between objects and the specifications of the problem and what is to be
not prescribing how the system should solve a task by computed.
a fixed sequence of instructions. And second, there is
no distinction between data and program, between Try the following goals one after other and note
data retrieval and computation. In each case we the output after each goal
determine one or more arguments of a relation using
the relations given by the program. ?- X =.. [child, ann, jane].

In these aspects, Prolog is substantially different from ?- X =.. [name, billy, kid], Y =.. [profession, thief], Z
procedural languages like C, ForTran or Pascal. When =.. [gunman, X, Y].

2
• Structures are constructed by means of
?- beatles([john, paul, george, ringo]) =.. X. functors. Each functor is defined by its name
and arity (number of arguments).
The operator ‘=..’ (univ operator) is a built-in predicate • The type of object is recognized entirely by its
(or procedure) which can be used for constructing syntactic form.
arbitrary Prolog structure. It can be used in both • The lexical scope of variables is one clause.
directions: to construct a structure from a list and to Thus the same variable name in two clauses
construct a list from a structure. means two different variables.
• Structures can be naturally pictured as trees.
Try the following Prolog program which tests Prolog can be viewed as a language for
whether list1 is longer than list2 processing trees.
• The matching operation takes two terms and
% longer(List1, List2) tries to make them identical by instantiating
longer([_|_], []). the variables in both terms.
longer([_|TailOfFirst], [_|TailOfSecond]) :-
• Matching, if it succeeds, results in the most
longer(TailOfFirst, TailOfSecond).
general instantiation of variables.
Try the following program which finds the • The declarative semantics of Prolog defines
number of elements in a list whether a goal is true with respect to a given
program, and if it is true, for what instantiation
length([], 0). of variables it is true.
length([_|Tail], N) :- • A comma between goals means the
length(Tail, LenTail), conjunction of goals. A semi-colon between
N is LenTail + 1. goals means disjunction of goals.
• The procedural semantics of Prolog is a
PROLOG (Some Tips) procedure for satisfying a list of goals in the
• Prolog programs can be extended, by simply context of a given program. The procedure
adding new clauses. Even at run-time! outputs the truth or falsity of the goal list and
• Prolog clauses are of three types: facts, rules the corresponding instantiation of variables.
and questions. The procedure automatically backtracks to
examine alternatives.
• Facts declare things that are always,
unconditionally true. • The declarative meaning of programs in ‘pure
Prolog’ does not depend on the order of
• Rules declare things that are true depending
clauses and the order of goals in the clauses.
on a given condition.
• The procedural meaning does depend on the
• By means of questions the user can ask the
order of goals and clauses. Thus the order can
program what things are true.
affect the efficiency of the program; an
• Prolog clauses consist of the head and the unsuitable order may even lead to infinite
body. The body has a list of goals separated by recursive calls.
commas. Commas are understood as
• Given a declaratively correct program,
conjunctions.
changing the order of clauses and goals can
• Facts are the clauses that have the empty improve the program’s efficiency while
body. Questions only have the body. Rules retaining its declarative correctness.
have the head and the (non-empty) body. Reordering is one method of preventing infinite
• In the course of computation, a variable can be looping.
substituted by another object. We say that a • There are other more general techniques,
variable becomes instantiated. apart from reordering, to prevent indefinite
• All variables are assumed as universally looping and thereby make programs
quantified and are read as ‘for all’. Alternative procedurally robust.
readings are, however, possible for variables • Prolog programming consists of defining
that appear only in the body. For example, relations and querying about relations.
• A prolog program consists of clauses. These
hasachild(X) :- parent(X, Y).
are of three types: facts, rules and questions.
can be read in two ways: • A relation can be specified by facts, simply
stating the n-tuples of objects that satisfy the
(a) For all X and Y, if X is a parent of Y then X relation, or by stating rules about the relation.
has a child. • A procedure is a set of clauses about the same
(b) For all X, X has a child if there is some Y relation.
such that X is a parent of Y. • Querying about relations, by means of
questions, resembles querying a database.
• Simple objects in Prolog are atoms, variables Prolog’s answer to a question consists of a set
and numbers. Structured objects, or structures, of objects that satisfy the question.
are used to represent objects that have several • In Prolog, to establish whether an object
components. satisfies a query is often a complicated process
that involves logical inference, exploring
among alternatives and possibly backtracking.

3
All this is done automatically by the Prolog )
system and is, in principle, hidden from the ),
user. gfx_end( Win ).
• Two types of meaning of Prolog programs are
distinguished: declarative and procedural. The
declarative view is advantageous from the
programming point of view. Nevertheless, the /* Example file: mci.pl
procedural details often have to be considered MCI Functions for WIN-PROLOG - Brian D Steel
by the programmer as well. =================================
========
A trial version of Developer’s Edition of WinProlog The mci/1 and mci/2 predicate are used to send
compiler can be downloaded freely from command strings to the WINMM.DLL (Windows
http://www.lpa.co.uk MultiMedia) API, and permits supported files to be
played under Prolog control. For example:
Please find below some WinProlog programs, taken ?- mci( `play \windows\tada.wav` ).
from examples folder (directory) of WinProlog. plays the Windows "TADA" sound file, TADA.WAV,
while:
/* Example File: Eg_gfx.pl ?- mci( `play d:\videos\pcmag.avi`, Result ).
A Simple Graphics Demo displays and runs the "PCMAG" video file, and returns
Dave Westwood and Brian D Steel the result. Assuming that the files are available at the
================================= specified locations*/
The gfx_eg/0 predicate runs a demonstration graphics
example which displays a dialog containing a "Grafix" % perform the given MCI command and check the
window filled with a rectangle and an ellipse. The result
example shows how a paint message is handled so as
to refresh only the portion of the window that needs mci( Command ) :-
repaint.*/ catch( Error, mci(Command,(Return,_)) ),
!,
% create the dialog, set its handler and then show the throw( Error, mci(Command) ),
dialog ( Return = 0
-> true
gfx_eg :- ; Return = -1
create_gfx_eg, -> fail
window_handler( gfx_eg, gfx_eg_handler ), ; Code is Return + 10000,
show_dialog( gfx_eg ). throw( Code, mci(Command) )
).
% create the grafix example dialog windows
% perform given MCI command and return result
create_gfx_eg :-
wdcreate( gfx_eg, mci( Command, Result ) :-
`Graphics Example`, 240, 83, 146,197, fcreate( mci, [], -2, 256, 0 ),
[ws_sysmenu, ws_caption] ), catch( Error, winapi((winmm,mciSendStringA),
wccreate( (gfx_eg,900), [Command,mci,256,0],0,Return) ),
grafix, `Grafix`, 16, 16, 112, 96, !,
[ws_child, ws_border, ws_visible] ), wintxt( mci, 0, 0, String ),
wccreate( (gfx_eg,1), fclose( mci ),
button, `Ok`, 32, 128, 80, 32, throw( Error, mci(Command,Result) ),
[ws_child, ws_visible, ws_tabstop, Result = (Return,String).
bs_pushbutton] ).
Bibliography
% close message is handled by atom "close"
1. Bratko Ivan, “Prolog Programming for Artificial
gfx_eg_handler( _, msg_close, _, close ). Intelligence”, Indian Reprint, Pearsoned Education
2. Burnhan, W D , Hall A R, “Prolog Programming and
% handle the "ok" button by returning the atom "ok" Applications”, Macmillan Education Ltd.
3. Clocksin W F, Mellish C S, “Programming in Prolog”,
gfx_eg_handler((gfx_eg,1), msg_button, _,ok). Narosa Publisjing House, New Delhi
4. Sterling L, Shapiro L, “The Art of Prolog – Advanced
% handle paint messages by starting, drawing some Programming Techniques”, MIT Press
graphics, and ending 5. I Kononenko and N Lavrac, “Prolog Through
Example: A practical programming guide”, Galgotia
gfx_eg_handler( Win, msg_paint, grafix, _ ) :- Publications (Pvt) Ltd
gfx_paint( Win ), 6. P Ross, “Advanced Prolog”, Addison-Wesley
gfx( ( rectangle( 10, 10, 100, 80 ), 7. N Ford, “Prolog Programming”, John Wiley
( brush = stock(gray_brush)
-> ellipse( 10, 10, 100, 80 )
)

You might also like