Notice that next to lambda, n appears without parentheses. Scheme will accept any
number of parameters; in this case, create a list of the parameters, and pass the list to the function giving the
list the name n.
58 SOFTWARE [CHAP. 4
(define sum
(lambda n
(cond ((null? n) 0)
( (null? (cdr n)) (car n) )
( else (+ (car n) (listSum (cdr n))))
)))
The code for sum is similar to listSum in its checking for the length of n (the set of parameters in the
case of sum), but if the number of parameters is two or greater, sum uses the listSum function to compute
the sum of elements 2 through n. That is because listSum expects a list as an argument, whereas sum expects
one or more separate arguments that get concatenated into a new list. If sum were to recursively call itself passing
(cdr n), the next call to sum would create ((cdr n)), a list of one element (the element is another list,
the cdr of the list of parameters), and the second line of cond would return a list instead of a number.
Our version of sum now behaves like ???+??™ and will accept any number of parameters and return the sum.
> (sum 2 4 5 6)
17
A more elegant solution accepts the list, builds a new expression by putting the ???+??™ in front of the list, and
passes the new list to the Scheme eval function directly.
Pages:
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168