2015-12-14 33 views
-2

我想寫一個函數,該函數從列表的任何 級別刪除所有出現的原子。我的代碼:lisp從列表中刪除所有出現的信息

(defun sterge (e l) 
    (cond 
    ((and (atom l) (equal e l)) nil) 
    ((atom l) (list l)) 
    (t (list (mapcan '(lambda (l) (sterge e l)) l))))) 

(defun sterg (e l) 
    (car (sterge e l))) 

當我執行它給了我:

(sterg '(1 2 (1 3)) 1) 
1 

我把任何價值,它給了我1,什麼是錯的?

+0

許多事情在這裏說,但只是基礎知識 - 你是不是用反向參數調用這個函數? 'e'是元素,'l'是列表,對嗎? – uselpa

+0

然後你只需要在'(lambda ...)'前面刪除引號就可以了。 – uselpa

+0

它的工作得益於您的意見,但@uselpa,爲什麼它刪除報價後工作? – Nero

回答

1

如果(remove-all '((1 2 3) (3 1 2 (4 3) 5 3)) 3)評估爲'((1 2) (1 2 (4) 5)),那麼下面的工作(方案):

(define (remove-all lst elt) 
    (if (null? lst) '() 
     (if (equal? (car lst) elt) 
      (remove-all (cdr lst) elt) 
      (cons (if (pair? (car lst)) 
        (remove-all (car lst) elt) 
        (car lst)) 
       (remove-all (cdr lst) elt))))) 

相反,如果(remove-all '((1 2 3) (3 1 2 (4 3) 5 3)) 3)評估爲'((1 2 #f) (#f 1 2 (4 #f) 5 #f))再考慮:

(define (deep-map fn lst) 
    (if (null? lst) '() 
     (cons (if (pair? (car lst)) 
       (deep-map fn (car lst)) 
       (if (null? (car lst)) '() 
        (fn (car lst)))) 
       (deep-map fn (cdr lst))))) 

(define (remove-all lst elt) 
    (deep-map (lambda (e) (if (equal? e elt) #f e)) lst))