Concepts of Programming Languages

(Sean Pound) #1
15.5 An Introduction to Scheme 691

The NULL? function tests its parameter to determine whether it is the empty
list and returns #T if it is. Consider the following examples:

(NULL? '(A B)) returns #F
(NULL? '()) returns #T
(NULL? 'A) returns #F
(NULL? '(())) returns #F

The last call yields #F because the parameter is not the empty list. Rather, it is
a list containing a single element, the empty list.

15.5.10 Example Scheme Functions


This section contains several examples of function definitions in Scheme.
These programs solve simple list-processing problems.
Consider the problem of membership of a given atom in a given list that
does not include sublists. Such a list is called a simple list. If the function is
named member, it could be used as follows:

(member 'B '(A B C)) returns #T
(member 'B '(A C D E)) returns #F

Thinking in terms of iteration, the membership problem is simply to com-
pare the given atom and the individual elements of the given list, one at a time
in some order, until either a match is found or there are no more elements in
the list to be compared. A similar process can be accomplished using recur-
sion. The function can compare the given atom with the CAR of the list. If they
match, the value #T is returned. If they do not match, the CAR of the list should
be ignored and the search continued on the CDR of the list. This can be done by
having the function call itself with the CDR of the list as the list parameter and
return the result of this recursive call. This process will end if the given atom
is found in the list. If the atom is not in the list, the function will eventually be
called (by itself ) with a null list as the actual parameter. That event must force
the function to return #F. In this process, there are two ways out of the recur-
sion: Either the list is empty on some call, in which case #F is returned, or a
match is found and #T is returned.
Altogether, there are three cases that must be handled in the function: an
empty input list, a match between the atom and the CAR of the list, or a mis-
match between the atom and the CAR of the list, which causes the recursive
call. These three are the three parameters to COND, with the last being the
default case that is triggered by an ELSE predicate. The complete function
follows:^6


  1. Most Scheme systems define a function named member and do not allow a user to redefine
    it. So, if the reader wants to try this function, it must be defined with some other name.

Free download pdf