Next: What You Should Up: Lists Previous: Some Possible Matches

### A Recursive Program Using Lists

We make use of a built-in predicate called write/1 to write out all the elements of a list in order. Note that the argument of write/1 must be a legal Prolog term.

write/1 is a side-effecting predicate. It captures the logical relation of always being true but it also produces output which has no part to play in the logical interpretation. It is therefore hard to produce a declarative reading for this predicate despite its utility from the procedural point of view. There are a fair number of other predicates which suffer from this problem including consult/1 and reconsult/1.

To write out a list of terms, write out the first element and then write out the remainder (the tail).

```
print_a_list([]).

print_a_list([HT]):-

write(H),

print_a_list(T).

```
Note that this can be improved by printing a space between elements of the list. This requires you to add the subgoal write(' ') into the body of the second clause and before the recursive call to print_a_list/1.

This will write the elements out on a single line. If you wanted to write each element on a different line then you would need the built-in predicate nl/0.

The second clause of print_a_list/1 roughly captures the meaning above. Then what does the first clause achieve? Without the first clause, print_a_list/1 would produce the required output and then fail because it would have to handle the empty list ([]) which cannot be deconstructed. Although print_a_list/1 is a side-effecting predicate, the natural (procedural) reading is that it succeeds once it has printed the list of terms. The first clause handles the case of the empty list so that the predicate will always succeed if it is given a list of terms to print. Quite reasonably, it will fail if given a non-list.

Next: What You Should Up: Lists Previous: Some Possible Matches

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