14.3 List goals (Ad)


On this page, we look at three goals that relate to lists:

  1. | (list constructor)
  2. member
  3. length

| (list constructor)

Remember that a list is defined as:

  1. Either the empty list, called 'nil',
  2. Or a succession consisting of:
    1. The head of the list, which is an element,
    2. The tail of the list, which is a list.

The list constructor (which might also be termed the list destructor, depending on how you look at it) is used as follows:

head((H | T), H).

it must be read as: head has two arguments. The first consists of a list, which is constructed as a head H and a tail T. The second argument is the head H.

Because matching occurs left-to-right, the second argument, H, will have been given the value which is the head of the list in the first argument.

Thus if we say:

?- head((Peter,Paul,Mary), H).

the answer is:

{H = Peter}

Thus the list constructor can be used to separate a list into its head and its tail.


The member/2 goal takes two arguments:


where E must be an element, and L must be a list. It answers the question: Is E somewhere in the list L?

If we ask:

?- member(Paul, (Peter,Paul,Mary)).

we get the answer:


On the other hand, if we ask:

?- member(Bob, (Peter,Paul,Mary)).

we get the answer:


If we ask:

?- member(P, (Peter,Paul,Mary)).

We get the answer:

{P = Peter}
{P = Paul}
{P = Mary}

This is because backtracking occurs even after the query succeeds.


The length/2 goal takes one argument:


where L is a list and X is either an integer or a free variable. It counts the number of elements in the list.

For example,

?- length((Peter,Paul,Mary),X).


{X = 3}

Note that this is an example of using an argument which is a variable to return a value from a rule.


Next, we look at two meta-goals. Meta-goals are goals that have side-effects apart from succeeding or failing.

Prev: 14.2 Logical goals (Ad)
Up: 14 Prolog+CG (Ad)
Next: 14.4 Meta-goals (Ad)