用另一个 Common LISP 替换树中的元素

Replacing an element from a tree with another Common LISP

我正在尝试将树中的一个元素替换为另一个元素。到目前为止,我设法替换了原子,但它无法正确添加到列表中

代码:

(defun replacing (tree trl wrl)
  (cond
    ((null tree) nil)
    ((atom tree)
     (cond ((eql tree trl) (list wrl))
           (t (list tree))))
    (t (apply 'nconc (mapcar #'(lambda (x) (replacing x trl wrl))
                             tree)))))

示例:(replacing '(A (B) (C (D) (E))) 'D 'W) -> (A (B) (C (W) (E)))

我得到的是:(A B C W E)

有什么要更改的想法吗?

在原子的情况下,只是 return 原子或其替换。你return一个列表。

如果是树,请使用 mapcar 将函数映射到子树上。去掉 NCONC.

Common Lisp 已在名称 subst:

下提供此功能
CL-USER 1 > (subst 'W 'D '(A (D) (C (D) (D))))
(A (W) (C (W) (W)))

代码:

(defun replacing (tree trl wrl)
  (cond
   ((null tree) nil)
   ((atom tree)
    (if (eql tree trl) wrl tree))
   (t (mapcar #'(lambda (x)
                  (replacing x trl wrl))
              tree))))