Following the
function cond is a list of condition/action pairs. Cond tests the first condition and, if it??™s true, cond executes
the associated action. If the first condition is false, cond checks the second condition. If the second condition
is true, cond executes the action associated with the second condition. There can be any number of conditions,
and cond will execute only the action associated with the first true condition. At the end can be an else condition
that cond will execute if no other condition is true. The else condition is not required, however.
The listSum function tests to see whether the list it was passed is null. If so, the function returns 0.
If not, then it tests to see if the cdr of the list is null. That will be true if the list consists of a single element,
and in that case the function will simply return the value of the first and only element. Otherwise, the function
recursively adds the first element of the list to the sum of the elements in the back (cdr) of the list.
When we evaluate listSum, we get the correct result:
> (listSum (list 2 4 5))
11
We can go one step further and make a function that behaves like the ???+??™ function, which accepts any
number of addends.
Pages:
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167