COM1340 - Winter 2003 Flat recursion on lists January 15, 2003 |
'((foo) (bar) (baz)) '(((((((42)))))))
we often are interested in traversing just the spine of a list.
That is, we often want to inspect just the elements at the
top level of the list -- which may themselves be lists --
without traversing those elements. We have already seen how
to take the length of a list. This handout looks at
some other typical uses of ``flat recursion'' on lists.
There are some Scheme forms we'll need, so let's cover these first.
A cond is a multi-way conditional (if only allows two branches).
The syntax is:
(cond [q1 a1] [q2 a2] ... [else an])
where the qs are questions, and the as are answers.
The Scheme evaluator checks the questions from top to bottom.
If any question is non-#f, the value of the corresponding
answer is the result of the cond. The else question
is always true. A cond does not need to have an else:
in that case, the result of the cond is unspecified if no
question returns non-#f.
The following forms are short-circuiting.
(and exp ...)
evaluates each of its arguments, left to right. As soon as an argument returns #f, the and returns #f. If all the expressions return non-#f, the and returns the value of the last argument. Observe: if each exp is the application of a predicate, the and returns either #t or #f.
(or exp ...)
evaluates its arguments left to right. If any returns non-#f, that's the value of the or. Otherwise, if all the arguments return #f, the or returns #f.