Information Technology Reference
In-Depth Information
is above another has
some number
of intermediate blocks. As in that section, writing
recursive programs is a two-step operation:
Write clauses to handle the
n
=
0 case. This means writing clauses to handle the
empty list with no elements.
Write clauses to handle the
(
n
+
1
)
case, on the assumption that the
n
case is
already taken care of.
This is where the
[H|T]
notation comes in very handy. Clauses that handle a
list
[H|T]
with
(
+
)
elements are written under the assumption that there are
already clauses to take care of the list
T
with
n
elements.
n
1
7.2.1 Some example list predicates
The following four examples of recursive predicates over lists illustrate this two-step
operation.
Example 1: List of people
Suppose there already is a predicate
person
(
)
x
that holds when
x
is a person. To
be defined is another predicate
person_list
(
)
, that holds when
z
is a list whose
elements are all people. So the desired behavior is this:
?- person_list([john,sue,george,harry]).
Yes
?- person_list([john,5,harry]).
No
z
This predicate will need to go through and check each element of the list. Therefore
it needs to be a recursive predicate.
1.
Write clause(s) to handle the empty list. The list with no elements is trivially a
list whose elements are all people:
% The empty list is a (trivial) list of people.
person_list([]).
2.
Write clauses to handle the list
[H|T]
, assuming that the predicate already works
for the list
T
.
The elements of the list
[H|T]
are all people if the head
H
is a person and all the
remaining elements in
T
are people. Assume that
person_list(T)
will correctly
determine whether the elements in
T
are all people.