Search code examples
listschemecons

Removing Item from List in Scheme leaves empty null list element


I have the following code:

 (define (atom? x)
   (and (not (null? x))
   (not (pair? x)))) 


 (define delete 
   (lambda (atom l)
     (cond
       ((null? l) '())
       ((atom? l) 
        (cond 
          ((not(eq? atom l)) l)
          (else '())
        )
       ) 
       (else (cons (delete atom (car l)) (delete atom (cdr l))) )
     )
   )  
  ) 

The goal is to remove a certain character from this list. For instance,

 (delete 'a '(a b a) )  ==> (b)

Instead of this I am getting:

  (delete 'a '(a b a) )==> (() b ())

I am brand new to scheme. I have tried not returning anything if the value is found, however that just makes it behave like:

 (delete 'a '(a b a) )==> (#<void> b #<void>)

Any ideas? Many thanks!


Solution

  •  (define delete
          (lambda (atom l)
               (cond
                    ((null? l) '())
                    ((atom? (car l))
                         (cond
                              ((eq? atom (car l)) (delete atom (cdr l)))
                              (else (cons (car l) (delete atom (cdr l))))
    
                         )
                    )
                    (else (cons (delete atom (car l)) (delete atom (cdr l))))
                )
          )
      )  
    

    This solution is more basic and easier to understand from the fundamentals.