every recursive pattern, an action is performed on every
element of a list.
The basic pattern is:
cons, with the results of acting on the rest.
Here is example:
(defun square-each (numbers-list) "Square each of a NUMBERS LIST, recursively." (if (not numbers-list) ; do-again-test nil (cons (* (car numbers-list) (car numbers-list)) (square-each (cdr numbers-list))))) ; next-step-expression
(square-each '(1 2 3)) ⇒ (1 4 9)
numbers-list is empty, do nothing. But if it has content,
construct a list combining the square of the first number in the list
with the result of the recursive call.
(The example follows the pattern exactly:
nil is returned if
the numbers’ list is empty. In practice, you would write the
conditional so it carries out the action when the numbers’ list is not
print-elements-recursively function (see Recursion with a List) is another example of an
pattern, except in this case, rather than bring the results together
cons, we print each element of output.
print-elements-recursively function looks like this:
(setq animals '(gazelle giraffe lion tiger))
(defun print-elements-recursively (list) "Print each element of LIST on a line of its own. Uses recursion." (when list ; do-again-test (print (car list)) ; body (print-elements-recursively ; recursive call (cdr list)))) ; next-step-expression (print-elements-recursively animals)
The pattern for