The Prolog Tutorial:

Writing Prolog programs & the exam

 

At this stage you should be quite comfortable using Prolog. You should be able to write procedures that use the built-in predicates of the language. You will need to do this for the exam.

The aims of this tutorial is to present a sample question and show how we might go about answering it.

Sample Question

This is actually Q1. off the 1999 paper:

Write a predicate reread/2 whose first argument is 1 or 0 and whose second argument is a list. If the first argument is 1, this predicate prompts for a filename and reads the list of numbers from that file into its second argument. If the first argument is 0, this predicate reads in numbers from the keyboard and stores them in the list.

In other words, reread/2 has the following behaviour:

?- reread(1,A).
	filename: input.
	A = [3,5,7,[9,17,23],5]

?- reread(0,A).
	input list: [3,5,9,[3,5,9],2].
	A = [3,5,9,[3,5,9],2]

 

Getting an answer

On the first reading this is what we should note - we are being asked to write a procedure which has two cases. One that will read a list of numbers from another from the user. So we have:

% Case 1

reread( 1, A )...

% Case 2

reread( 2, A )...

Now we need to think of the built-in predicates we'll need to carry perform the task we have been asked to. We will need read/1, write/1, nl/0, see/2, seen and maybe seeing/1. How do we know we need these?

Well, firstly the sample output of the predicate shows a prompt e.g. 'filename' we will need write/1 and probably nl/0 to generate this. Secondly we use read/1 to gather input from both the user or from a file. So we definitely need this. Thirdly if we are opening a file we have to use see/1 and after we have read from this file we close the input stream with seen/0.

Putting all this together we should get.

% Case 1

reread( 1, A ) :-

nl,

write( ' Input list: ' ),

read( A ).

% Case 2

reread( 2, A ) :-

nl,

write( ' Filename: ' ),

read( Filename ),

see( Filename ),

read( A ),

seen.

This should work. Sure, it could be made more robust but this procedure does everything that it is supposed to.

A short note on Prolog style

Always comment your code. You will notice that generally the procedures as written here are spread out and not jumbled close together. Although Prolog wouldn't mind this, it won't be easy to read. The body of a rule is usually tabbed. 

Good Luck!

Author - Jer Hayes - 2000