从 LISP 中带有子列表的列表中删除所有 nil
Remove all nils from a list with sublists in LISP
我有一个包含多个子列表的列表。其中一些具有我需要摆脱的 NIL 元素。我只能使用基本功能(NOT、EQL、CONS 等。)
(defun trgni (lista)
(cond
((null lista) nil)
((not (atom (car lista))) (cons (trgni (car lista)) (trgni (cdr lista))))
((eql nil (car lista)) (trgni (cdr lista)))
(t (cons (car lista) (trgni (cdr lista))))))
我的代码有一个问题,当我有一个仅包含 nils 的子列表时会发生这种情况。例如:
(trgni '((NIL ((7))) (8 (9 (10 ((11))) 12)) (13 (NIL NIL))))
我的代码给我:
((((7))) (8 (9 (10 ((11))) 12)) (13 NIL))
根据 the hyperspec ()
只是书写符号 nil
的另一种表示法,但是由于它是完全相同的对象,CL 在打印时将只使用一种表示法。它不会是替代符号,除非特定的实现将它作为可配置的功能。
在您的函数中,当您处理 car
时,您需要检查结果是否为空。像这样:
(let ((a (trgni (car lista))))
(if (null a)
(trgni (cdr lista)) ; don't include this null value
(cons a (trgni (cdr lista))))) ; include since it's not null
请注意,这仅适用于嵌套列表,如 '(1 (nil nil nil) 2)
,应该变为 (1 2)
,但如果参数为 (nil nil nil)
怎么办?然后它将没有任何合理的值,除了 nil
将其评估为 nil
是空列表。
我有一个包含多个子列表的列表。其中一些具有我需要摆脱的 NIL 元素。我只能使用基本功能(NOT、EQL、CONS 等。)
(defun trgni (lista)
(cond
((null lista) nil)
((not (atom (car lista))) (cons (trgni (car lista)) (trgni (cdr lista))))
((eql nil (car lista)) (trgni (cdr lista)))
(t (cons (car lista) (trgni (cdr lista))))))
我的代码有一个问题,当我有一个仅包含 nils 的子列表时会发生这种情况。例如:
(trgni '((NIL ((7))) (8 (9 (10 ((11))) 12)) (13 (NIL NIL))))
我的代码给我:
((((7))) (8 (9 (10 ((11))) 12)) (13 NIL))
根据 the hyperspec ()
只是书写符号 nil
的另一种表示法,但是由于它是完全相同的对象,CL 在打印时将只使用一种表示法。它不会是替代符号,除非特定的实现将它作为可配置的功能。
在您的函数中,当您处理 car
时,您需要检查结果是否为空。像这样:
(let ((a (trgni (car lista))))
(if (null a)
(trgni (cdr lista)) ; don't include this null value
(cons a (trgni (cdr lista))))) ; include since it's not null
请注意,这仅适用于嵌套列表,如 '(1 (nil nil nil) 2)
,应该变为 (1 2)
,但如果参数为 (nil nil nil)
怎么办?然后它将没有任何合理的值,除了 nil
将其评估为 nil
是空列表。