替换lisp中的函数

时间:2011-03-29 20:40:03

标签: lisp common-lisp

我想替换给定列表中的单词,但是当列表

给出替换单词时,它很难

例如(myreplace'((狗猫)(可爱可爱))'(我的狗很可爱)) - > (我的猫很可爱)

帮帮我!

2 个答案:

答案 0 :(得分:1)

这是一个递归版本:

(defun myreplace (subst-alist replace-in)
  (when replace-in
    (let ((found (assoc (car replace-in) subst-alist :test #'eq)))
      (cons 
       (if found
           (cadr found)
         (car replace-in))
       (myreplace subst-alist (cdr replace-in))))))

如果您更喜欢这种方法,那么这是一个迭代版本:

(defun myreplace (subst-alist replace-in)
  (let (result)
    (dolist (word replace-in (reverse result))
      (let ((found (assoc word subst-alist :test #'eq)))
        (push (if found (cadr found) word)
              result)))))

答案 1 :(得分:0)

以下解决方案使用reduce为每个新旧对调用substitute,逐步转换原始序列:

(defun myreplace (substitutions sequence)
  (reduce (lambda (seq substitution)
            (destructuring-bind (old new) substitution
              (substitute new old seq)))
          substitutions
          :initial-value sequence))

编辑:Trey使用assoc(不是assq,即Emacs Lisp)来寻找替换的想法非常好。通过使用内置支持构建新列表的运算符(即mapcarloopcollect子句,可以简化使用它:

(defun myreplace (substitutions list)
  (mapcar (lambda (elt)
            (let ((substitution (assoc elt substitutions)))
              (if substitution
                  (second substitution)
                  elt)))
          list))

(defun myreplace (substitutions list)
  (loop for elt in list
     for substitution = (assoc elt substitutions)
     when substitution collect (second substitution)
     else collect elt))