title: Delete occurences of item from non-linear list
body: <p>I am trying to delete all occurrences of an element from a list, from any levels of the list. <strong>I am required to use a map function though</strong>. I am using Common Lisp. For example I'd want to be able to do:</p>
  
  <pre><code>(fdelete '(1 2 3 4 (3)) 3) =&gt; (1 2 4)
  </code></pre>
  
  <p>What I've tried so far:
  This function will do what's needed, sort of. It will replace all occurences of the given element with NIL, so it's not exactly what I want.</p>
  
  <pre><code>(defun fdelete (l e)
      (cond
          ((null l) 0)
          ((equal l e) nil)
          ((atom l) l)
          (t (mapcar (lambda(l) (fdelete l e )) l ))
      )
  )
  </code></pre>
  
  <p>This will do</p>
  
  <pre><code>(fdelete '(1 2 3 4 (3)) 3) =&gt; (1 2 NIL 4 (NIL)) 
  </code></pre>
  
  <p>My second try is with the mapcap function, since this one won't return a list the same size as the input list.
  This will do what's needed, but it will 'destroy' my initial list, as in, it will bring all sublists 'to surface'. </p>
  
  <pre><code>(defun fdelete (l e)
      (cond
          ((null l) 0)
          ((equal l e) nil)
          ((atom l) (list l))
          (t(mapcan(lambda(x) (fdelete x e ))l ))
      )
  )
  </code></pre>
  
  <p>So this indeed does <code>(fdelete '(1 2 3 4 (3)) 3) =&gt; (1 2 4)</code>
  but it will also do it wrong if I for example try this:</p>
  
  <pre><code>(fdelete '(1 2 3 (4) (3)) 3)) =&gt; (1 2 4)
  </code></pre>
  
  <p>I'd want it to do <code>(fdelete '(1 2 3 (4) (3)) 3)) =&gt; (1 2 (4))</code></p>
  
  <p>I hope my question is well formed and detailed enough, and I am providing working examples. Can someone give me a few hints on how to solve this problem?</p>