More Prolog

Comments

There are two ways to write comments in Prolog. A multi-line comment is written just as in C. /* … */

A single line comment begins with a % and ends at the end of a line.

For example:
see[cubedata]. % This predicate opens the file cubedata for reading.

I/O Streams

Prolog uses built in predicates to redirect its input and output streams. The default source and destination for input and output respectively are the keyboard and screen, both of which are referred to as user.

The command to change the input stream to a file is
see(filename).
The filename must be in lowercase. Note that this is treated as a predicate that is true as long as the file can be opened and has the side effect of redirecting the input stream.

The command to change the output stream to a file is
tell(filename).
The same rules as above apply.

To return to the standard input or output streams use see[user] or tell[user].

Read and Write

Prolog also has read and write predicates that are used to get data from the current input stream or send data to the current output stream.

For example:
read(X).
gets a value or string from the current input an assigns it to X. Note that X must be a variable, so it must begin with an upper-case letter.

For example, here is a Prolog program that uses read, write and see to calculate the cubes of a series of numbers read from a file.

precube:-see(cubedata), cube, see(user).
/* Opens the file cubedata for reading, tests the truth of the predicate cube (or executes the procedure cube, if you want to think procedurally), returns to the standard input stream.*/

cube :- read(X), process(X).
/* Reads a piece of data, tests the truth (executes) process for that piece of data. */

process(stop) :- !
/* The symbol !, pronounced "cut," means stop testing the current predicate. */

process(N) :- C is N*N*N, write(C), cube.
/* Process N is true if C is N cubed, and C has been written, and cube is true again (this acts as a loop as Prolog retests/reexceutes the cube predicate. */

The proceeding program works as long as there is a file named cubedata with appropriate data in it. For example the file
9.
5.
2.
3.
stop.
Note the period and newline after each data entry and the stop at the end is used to halt the process predicate in the program.

Unfortunately the output of this program on this data file would be:
729125827
which is correct (729 125 8 and 27) but hard to read. A better version of the process predicate is:
process(N) :- C is N*N*N, write(‘Cube of ‘), write (N), write(‘ is ‘), write(C), nl, cube.

Note the quotes for literal strings and the nl for a newline.