演習1.3

リスト中に含まれるアトムの数を返す関数count-atomsを作る。

;;; Exercise 1.3

(defun count-atoms (lst)
  (cond ((null lst) 0)
	((listp (first lst)) (+ (count-atoms (first lst))
				(count-atoms (rest lst))))
	(t (+ 1 (count-atoms (rest lst))))))

と作ってみたけど、実行してみたら

(count-atoms '(a (b) c)) ;==> 3
(count-atoms '(a nil c)) ;==> 2

という結果になった。後者は(a () c)と同じなのでアトムの数は2としたけど、nilはアトムでもある*1ので、本来なら3を返すべきなのかもしれない。

……と解答を読むとどちらのケースにも対応できる答えが載っていた。

*1:例えば(atom nil)とするとtが戻る。