我想在给定的列表中替换单词,但是当替换单词是由列表给出的时候,这是非常困难的
例如(myreplace‘((狗猫)(可爱可爱))’(我的狗很可爱)) -> (我的猫很可爱)
帮帮我!
发布于 2011-03-30 05:23:48
下面是一个递归版本:
(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)))))发布于 2011-03-30 07:12:55
下面是一个解决方案,它使用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)来查找替换的想法非常好。通过使用内置支持构建新列表的运算符,即带有collect子句的mapcar或loop,可以简化该操作:
(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))https://stackoverflow.com/questions/5478648
复制相似问题