Lisp-替换列表中元素的所有外观 [英] Lisp - replace all the appereances of an element in a list
问题描述
我尝试在所有主列表级别上用另一个列表K替换列表中的某个元素E。
I try to replace a certain element E in a list with another list K at all the main list levels.
(defun replaceList(l e k)
(cond
((null l) nil)
((equal e (car l)) (cons k (replaceList (cdr l) e k)))
((listp (car l))
((equal e (car (car l))) (cons k (replaceList (cdr (car l)) e k))))
(t (cons (car l) (replaceList (cdr l) e k)))))
示例:
(replaceList '(3 1 2 (6 1) 7 (5 (5 (3 1))) 9) '1 '(99 99))
--> (3 (99 99) 2 (6 (99 99)) 7 (5 (5 (3 (99 99) ) ) ) 9)
我得到了带有lambda表达式的错误消息。
I get something with lambda expression as error message.
此外,我尝试使用 listp(car l)
block:
(((listp(car l))(cons k(replaceList(cdr(car l))ek)))
。
我得到一些奇怪的东西:
(2 1 3(6 1 7)7 1 2)
-> (2( 99 99)3(99 99)(99 99)7)
Also,i tried instead of the listp(car l)
"block" :
((listp (car l)) (cons k (replaceList (cdr (car l)) e k)))
.
I get something weird :
(2 1 3 ( 6 1 7) 7 1 2 )
-> (2 (99 99) 3 (99 99) (99 99) 7)
推荐答案
错误
您的 lambda表达消息是由于 listp中
子句。请记住, Lisp括号是有意义的 。等于
的一组额外的括号
Error
Your "lambda expression message" is due to an extra set of parens around equal
in the listp
clause. Remember, Lisp parentheses are meaningful.
ANSI Common Lisp具有 subst
可以满足您的需求:
ANSI Common Lisp has subst
which does what you want:
(subst '(99 99) 1 '(3 1 2 (6 1) 7 (5 (5 (3 1))) 9) :test #'equal)
==> (3 (99 99) 2 (6 (99 99)) 7 (5 (5 (3 (99 99)))) 9)
您的算法
由于您是在树而不是 list 上进行操作(您说 所有
主列表级别),则应使用汽车
和 cdr
相同:
Your algorithm
Since you are operating on the tree, not list (you say "all the
main list levels"), you should treat car
and cdr
identically:
(defun my-subst (new old tree &key (test #'eql))
(cond ((funcall test old tree)
new)
((atom tree)
tree)
(t
(cons (my-subst new old (car tree) :test test)
(my-subst new old (cdr tree) :test test)))))
(my-subst '(99 99) 1 '(3 1 2 (6 1) 7 (5 (5 (3 1))) 9) :test #'equal)
==> (3 (99 99) 2 (6 (99 99)) 7 (5 (5 (3 (99 99)))) 9)
Or, simplified (without &key
and
funcall
):
(defun my-subst (new old tree)
(cond ((equal old tree)
new)
((atom tree)
tree)
(t
(cons (my-subst new old (car tree))
(my-subst new old (cdr tree))))))
这篇关于Lisp-替换列表中元素的所有外观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!