Epigrams on Programming の116番目がそれ。
apply と append と mapcar を組み合わせて使う。 まず名前のリストから肩書きをすべて外し、その結果の中で最後に現れるものを取り出す。
(defparameter *titles* '(Mr Mrs Miss Ms Sir Madam Dr Admiral Major General MD Jr Jr.) "A list of titles that can appear at the start of a name.") (defun mappend (fn the-list) (apply #'append (mapcar fn the-list))) (defun remove-titles (name) (mappend #'(lambda (x) (if (member x *titles*) nil (list x))) name)) (defun last-name (name) "select the last name from a name represented as a list." (first (last (remove-titles name)))) (last-name '(Rex Morgan MD)) ; => MORGAN (last-name '(Morton Downey\, Jr.)) ; => |Downey,|
CLHS: Function EXP, EXPT と同様の関数をつくる。
(defun power (b p) (if (> 1 p) 1 (* b (power b (- p 1))))) (power 3 2) ; => 9
アトムの数をすべて数え挙げる関数 count-all-atoms を作成していない。
cond を使わずに if を使う。
(defun count-atoms (exp) "Return the total number of non-nil atoms in the expression." (if exp ;; atom 関数は 1.10で出てくる (if (atom exp) 1 (+ (count-atoms (first exp)) (count-atoms (rest exp)))) 0)) (count-atoms '(a (b) c)) ; => 3 (count-atoms '(a nil c)) ; => 2
cond を使わずに if を使う。
(defun count-anywhere (item tree) "Count the times item appears anywhere within tree." (if (eql item tree) 1 (if (atom tree) 0 (+ (count-anywhere item (first tree)) (count-anywhere item (rest tree)))))) (count-anywhere 'a '(a ((a) b) a)) ; => 3
(defun dot-product (a b) (apply #'+ (mapcar #'* a b))) (dot-product '(10 20) '(3 4)) ; => 110