120 Logic Programming With Prolog
For non-empty lists, the first element is known as the head. The list remaining
after the first element is removed is called the tail. For example, the head of the list
[dog,cat,fish,man] is the atom dog and the tail is the list [cat,fish,man].
The head of list [x,y,mypred(a,b,c),[p,q,r],z] is the atom x. The tail is the list
[y,mypred(a,b,c),[p,q,r],z].
Some further examples of lists are:
[john,mary,10,robert,20,jane,X,bill]
[[john,28],[mary,56,teacher],robert,parent(victoria,albert),[a,b,[c,d,e],f],28]
[[portsmouth,london,glasgow],[portsmouth,london,edinburgh],[glasgow]]
9.2 Notation for Lists
Up to now lists have been written as a sequence of list elements written in order,
separated by commas and enclosed in square brackets. We will call this 'standard
bracketed notation'.
Lists are generally, although not always, written in this notation in queries
entered by the user at the system prompt, for example
?- X=alpha,Y=27,Z=[alpha,beta],write('List is: '),write([X,Y,Z]),nl.
List is: [alpha,27,[alpha,beta]]
However (with the exception of the empty list) lists are seldom written in this
way in a Prolog program. The explanation for this is that lists are most useful (and
generally only used) when the programmer does not know in advance how many
elements they will contain. If we know that a list will always contain three
elements, say a person's forename, surname and nationality, it would generally be
better to use a compound term with three arguments, such as person(john, smith,
british).
Lists are most valuable when the number of elements needed cannot be known
in advance and would probably vary from one use of the program to another. For
example, we might want to define a predicate that reads in information about an
organisation's purchases in a given financial year and writes out a list of all the
items of computer hardware or software purchased in the months from March to
June inclusive that cost more than a certain amount. In this case we would certainly
not wish to build in any assumption that the list will always have fifteen or any
other fixed number of elements. It might potentially be any number, from zero
upwards.
We need an alternative way of representing a list in a Prolog clause that does
not make any commitment to the number of elements it will have when the clause
is used. This is provided by the 'cons' (standing for list constructor) notation.
In this notation a list is written in a more complicated form than before, with
two parts joined together by the vertical bar character | which is known as the cons