Kamuycikap - SentenceDataBase

日々の勉強の記録を気分で書き綴るブログ

Emacs Lisp: 置換(改)

Emacs Lisp: 置換(改)

以前に作ったreplを、リストの入れ子対応にする。
前に作ったものは、第一引数のリストであるlstの中で、第二引数のoldと等しい要素すべてをnewで置き換える関数です。

(defun repl (lst old new)
  (cond
   ((null lst) nil)
   ((eq (car lst) old)
    (cons new (repl (cdr lst) old new)))
   (t (cons (car lst) (repl (cdr lst) old new)))))

(repl '(dog pig dog) 'dog 'rat) ;; => (rat pig rat)

この関数を、関数の入れ子対応に。

(defun repl* (lst old new)
  (cond
   ((null lst) nil)
   ((consp (car lst))
    (cons (repl* (car lst) old new)
          (repl* (cdr lst) old new)))
   ((eq (car lst) old)
    (cons new (repl* (cdr lst) old new)))
   (t (cons (car lst) (repl* (cdr lst) old new)))))

(repl* '(1 2 (2 9) (3 4 2)) '2 '9)  ;; => (1 9 (9 9) (3 4 9))