在 LISP 中修改/替换
我有一个名为修改列表的函数的实现,如下所示,但它仅适用于顶级列表。
(defun modify-list (old new a-list)
(cond
((null a-list) nil)
((eql (car a-list) old) (cons new (modify-list old new (cdr a-list))))
(T (cons (car a-list)(modify-list old new (cdr a-list))))))
CL-用户 16 : 6 > (修改列表'a'x'(padgca)) (PXDGCX) <-- 好!
CL-用户17:6> (修改列表'a'x'(pad(ga)ca)) (PXD (GA) CX) <----不好!
谁能帮助我使这个函数在嵌套列表上工作?
I have an implementation of a function called modify list shown below but it only works for top level lists.
(defun modify-list (old new a-list)
(cond
((null a-list) nil)
((eql (car a-list) old) (cons new (modify-list old new (cdr a-list))))
(T (cons (car a-list)(modify-list old new (cdr a-list))))))
CL-USER 16 : 6 > (modify-list 'a 'x '(p a d g c a))
(P X D G C X) <-- GOOD!
CL-USER 17 : 6 > (modify-list 'a 'x '(p a d (g a) c a))
(P X D (G A) C X) <----NOT GOOD!
can anyone help me make this function work on nested lists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不在更高层次上工作呢?这将使代码更简单...
基本上,您不必假设
x
必须是一个列表(实际上是一棵树),只需返回new
ifx
是old
,如果它是列表,则递归映射,否则返回x
不变...使用这种方法也
(modify 'a 'x 'a) --> ; X
(IMO 似乎是正确的)。Why not working at an higher level? It would make the code simpler...
Basically instead of assuming
x
must be a list (actually a tree) you just returnnew
ifx
isold
, recursively map if it's a list or otherwise returnx
unchanged...With this approach also
(modify 'a 'x 'a) --> X
(and that IMO seems right).这里有一个想法:
我无法访问 LISP 解释器(任何人都可以验证上述过程吗?),所以你必须先测试它!
Here's an idea:
I don't have access to a LISP interpreter (anyone can verify the above procedure, please?), so you'll have to test it first!