演習1.4

リスト中に特定のアトムが含まれる数を数える関数を作る。

(defun count-anywhere (x lst)
  (cond ((null lst) 0)
	((listp (first lst)) (+ (count-anywhere x (first lst))
				(count-anywhere x (rest lst))))
	(t (+ (if (eq x (first lst)) 1 0) (count-anywhere x (rest lst))))))

演習1.3で自分が作ったプログラムを発展させて、上記のように作ってみた。(count-anywhere x (rest lst))が2回出てくるのが汚いなぁと思いつつも、これでいいやと妥協。ちゃんと実行すると結果は出てるし。

(count-anywhere 'a '(a ((a) b) a)) ;==> 3

解答を見ると、やはり(count-anywhere x (first lst))と(count-anywhere x (rest lst))が一度ずつしか出てこないし、プログラムも読みやすい……。精進します。