every の再帰パターンでは、リストのすべての要素に対して処理が行われます。
基本パターンは:
nilを返す。
consを用いて処理対象の要素と、それ以外の要素への処理結果を結合します。
以下に例を示します。
(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
が空の場合は何もしない。ただし、内容がある場合は、リストの最初の数値の2乗と再帰呼び出しの結果を組み合わせたリストを作成する。
(この例はパターンに忠実に従っており、numbers’リストが空の場合はnilが返されます。実際には、numbers’リストが空でない場合に処理が実行されるよう、条件式を記述することになります。)
print-elements-recursively 関数(リストを用いた再帰を参照)は、every パターンのもう一つの例です。ただし、この場合は cons を用いて結果をまとめるのではなく、出力の各要素をプリントします。
print-elements-recursively 関数は次のようになります。
(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)
print-elements-recursively のパターンは以下の通りです: