next up previous contents
Next: Input/ Output Channels Up: Another Interlude: Input/Output Previous: Another Interlude: Input/Output

Testing a Predicate

Suppose that we want to test the predicate double/2 to see if it works for its intended inputs.

 
double(X,Y):-

Y is 2*X.

To do this, we write a test predicate:
 
test:-

read(X),

double(X,Y),

write(Y),

nl.

Here is a transcription of executing the query test:
 
?- test.

: 2.

4

yes

Note that, since we are using read/1 which only accepts valid Prolog terms terminated by a ``.'' followed by Return (in this case), we have to enter input integers as 2.!

Now to make this into a loop. The easy way is to recursively call test/0. We would prefer, however, to put in a test so that we can abort the loop. This requires an end-of-input marker.

 
test:-

read(X),

\+(X = -1),

double(X,Y),

write(Y),

nl,

test.

When we input the end-of-input marker (-1) we backtrack to read/1 which fails (for this Prolog implementation!) and test/0 fails as there are no other clauses. We could always add a second clause (after ---not before) which guaranteed that the goal test succeeded once the end-of-input marker was met.

Note that it is up to us to make sure that read/1 is never asked to process non-integer inputs. We could always define and use our own read_integer/1 to catch non-integer input.


Paul Brna
Mon May 24 20:14:48 BST 1999