2012-04-30 117 views
0

我需要從列表中刪除包含內部列表的元素。預定義元素也應該從每個內部列表中刪除。LISP - 使用嵌套列表從列表中刪除元素

我已經開始用下面的代碼工作:

(SETQ L2 '(a b (a 2 b) c 1 2 (D b (a s 4 2) c 1 2 a) a)) ; defined my list 

; Created a function for element removing 
(defun elimina (x l &optional l0) 
(cond ((null l)(reverse l0)) 
((eq x (car l))(elimina x (cdr l) l0)) 
(T (elimina x (cdr l) (cons (car l) l0)))) 
) 

(ELIMINA 'a L2) 

但不幸的是它消除了嵌套列表以外的唯一要素。

我試圖創建一個額外的功能,這將從內列表中刪除的元素。

(defun elimina-all (x l) 
(cond ((LISTP (CAR L))(reverse l)(elimina x (car l))) 
(T (elimina-all x (CDR L))) 
) 
) 

但仍不成功。

能否請你幫我去解決它?

預先感謝您。

+1

這是功課嗎?如果是,請添加標籤作業。 –

+4

你也應該正確地縮進你的代碼。因爲它現在很難閱讀。 –

回答

0

也許是這樣的:

(defun elimina (x l &optional l0) 
    (cond ((null l) (reverse l0)) 
     ((eq x (car l)) (elimina x (cdr l) l0)) 
     (T (elimina x (cdr l) (cons (if (not (atom (car l))) 
             (elimina x (car l)) 
             (car l)) 
            l0))))) 
+0

這是一個很好的解決方案,謝謝,但它不能從列表中移除一組元素,例如: (ELIMINA(a 2 b)L2) – e20

+0

在這種情況下,您需要將'( (如果(atom x)(eq x(car l))(member(car l)x))'' –

+0

使用'(member(car l)x)'將只從整個列表中刪除列表的第一個成員。但實際上,重點是從'(A(A(A 2 B))'列表(L2)中刪除'(A 2 B)'。 – e20

2

首先,我建議你讀這本書,至少,this page,它解釋(也提供了很好的例子!)如何移動一棵樹,但最重要的是,如何組合功能以從更簡單的任務中利用更復雜的任務。

;; Note that this function is very similar to the built-in 
;; `remove-if' function. Normally, you won't write this yourself 
(defun remove-if-tree (tree predicate) 
    (cond 
    ((null tree) nil) 
    ((funcall predicate (car tree)) 
    (remove-if-tree (cdr tree) predicate)) 
    ((listp (car tree)) 
    (cons (remove-if-tree (car tree) predicate) 
      (remove-if-tree (cdr tree) predicate))) 
    (t (cons (car tree) 
      (remove-if-tree (cdr tree) predicate))))) 

;; Note that the case of the symbol names doesn't matter 
;; with the default settings of the reader table. I.e. `D' and `d' 
;; are the same symbol, both uppercase. 
;; Either use \ (backslash) or || (pipes 
;; around the symbol name to preserve the case. Eg. \d is the 
;; lowercase `d'. Similarly, |d| is a lowercase `d'. 
(format t "result: ~s~&" 
     (remove-if-tree 
     '(a b (a 2 b) c 1 2 (D b (a s 4 2) c 1 2 a) a) 
     #'(lambda (x) (or (equal 1 x) (equal x 'a))))) 

下面是解決問題的一種方法的簡短示例。閱讀評論。

0

我一直在尋找相同的答案你,不幸的是,我無法完全理解上述這樣的答案,我只是在它的工作,最後我在Lisp中有一個非常簡單的功能,你想要做什麼。

(defun remove (a l) 
(cond 
    ((null l)()) 
     ((listp (car l))(cons (remove a (car l))(remove a (cdr l)))) 
     ((eq (car l) a) (remove a (cdr l))) 
     (t (cons (car l) (remove a (cdr l)))) 
     ) 
    ) 

該函數從兩個簡單的例子開始:'list is null'和'first element is a list'。在此之後,您將「神奇地」獲取列表的car和列表的cdr,而不包含給定的元素。爲了解決這個問題,你需要使用cons來將它們放在一起。