0

内部リストを含むリストから要素を削除する必要があります。事前定義された要素もすべての内部リストから削除する必要があります。

私は次のコードで作業を開始しました:

(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)))
)
)

しかし、それでも失敗しました。

私がそれを解決するのを手伝ってくれませんか?

前もって感謝します。

4

3 に答える 3

2

まず、この本を読むことをお勧めします。少なくともこのページでは、ツリーをトラバースする方法について説明しています(また、非常に良い例を示しています)が、最も重要なのは、関数を組み合わせてより複雑なものを活用する方法についてです。より単純なタスクからのタスク。

;; 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)))))

これは、問題に取り組む1つの方法の簡単な例です。コメントを読んでください。

于 2012-04-30T17:30:53.160 に答える
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)))))
于 2012-04-30T09:49:45.303 に答える
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))))
        )
    )

この関数は、「リストがnull」と「最初の要素がリスト」の2つの単純なケースで始まります。これに続いて、「魔法のように」carリストのとcdr、指定された要素のないリストのを取得します。それをリスト全体の答えになるように修正するには、を使用してそれらをまとめる必要がありますcons

于 2015-03-11T23:34:37.143 に答える