我试图用另一个树替换树中的元素。到目前为止,我设法替换原子,但它没有被正确地添加到列表中
代码:
(replacing '(A (B) (C (D) (E))) 'D 'W) -> (A (B) (C (W) (E)))
示例:(A B C W E)
我得到了什么:127.0.0.1 localhost
127.0.1.1 vagrant
# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
#hadoop
192.168.0.1 master
任何想法要改变什么?
答案 0 :(得分:4)
在原子的情况下,只需返回原子或其替代物。你返回一个清单。
如果是树,请使用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))))