在 LISP 中修改/替换

发布于 2024-12-11 23:18:42 字数 436 浏览 0 评论 0原文

我有一个名为修改列表的函数的实现,如下所示,但它仅适用于顶级列表。

(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

十级心震 2024-12-18 23:18:42

为什么不在更高层次上工作呢?这将使代码更简单...

(defun modify (old new x)
  (cond
    ((eq x old) new)
    ((listp x)
     (mapcar (lambda (y) (modify old new y)) x))
    (t x)))

基本上,您不必假设 x 必须是一个列表(实际上是一棵树),只需返回 new if xold,如果它是列表,则递归映射,否则返回 x 不变...

使用这种方法也 (modify 'a 'x 'a) --> ; X (IMO 似乎是正确的)。

Why not working at an higher level? It would make the code simpler...

(defun modify (old new x)
  (cond
    ((eq x old) new)
    ((listp x)
     (mapcar (lambda (y) (modify old new y)) x))
    (t x)))

Basically instead of assuming x must be a list (actually a tree) you just return new if x is old, recursively map if it's a list or otherwise return x unchanged...

With this approach also (modify 'a 'x 'a) --> X (and that IMO seems right).

醉殇 2024-12-18 23:18:42

这里有一个想法:

(defun modify-list (old new a-list)
  (cond ((null a-list) nil)
        ((not (listp (car a-list)))
         (if (eql (car a-list) old)
             (cons new (modify-list old new (cdr a-list)))
             (cons (car a-list) (modify-list old new (cdr a-list)))))
        (T (cons (modify-list old new (car a-list))
                 (modify-list old new (cdr a-list))))))

我无法访问 LISP 解释器(任何人都可以验证上述过程吗?),所以你必须先测试它!

Here's an idea:

(defun modify-list (old new a-list)
  (cond ((null a-list) nil)
        ((not (listp (car a-list)))
         (if (eql (car a-list) old)
             (cons new (modify-list old new (cdr a-list)))
             (cons (car a-list) (modify-list old new (cdr a-list)))))
        (T (cons (modify-list old new (car a-list))
                 (modify-list old new (cdr a-list))))))

I don't have access to a LISP interpreter (anyone can verify the above procedure, please?), so you'll have to test it first!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文