Delete element from a nested list while keeping the original nested structure CLISP

31 Views Asked by At

Is there a way to delete an element from a nested list while also keeping the nested structure intact?

For instance, for the list ((1 (2 (3 (3 4 5 (3 (3)))) 3 4) 3 3) 3 (3 3)) if we delete the element 3 then the result should be ((1 (2 ((4 5 (()))) 4)) ()), essentially the function should keep the previous list structure

I tried checking 3 cases:

a) if the current element is an atom and equal to the given number, then nothing should happen

b) if the current element is an atom and different than the given number, then it should be appended to the result

c) if the current element is a list, then the delete function should be applied to it (using mapcar and a lambda)

If I run my delete function on the list ((1 (2 (3 (3 4 5 (3 (3)))) 3 4) 3 3) 3 (3 3)) where the given number is 3, it outputs (1 2 4 5 4) instead of the expected outcome ((1 (2 ((4 5 (()))) 4)) ())

I believe it's because I turn the current element into a list (if it's equal to the given number) and then use append which removes the parentheses

(defun delete (no l)
    (cond
        ;; current element == given number
        ;; it shouldn't be added to the result -> nil
        ((and (atom l) (equal no l)) nil)
        ;; current element != given number
        ;; it is made into a list and added to the result
        ((and (atom l) (not (equal no l)))  (list l))
        ;; current element is a list
        ;; the delete function is applied to each element of the list using mapcar
        (t (apply 'append (mapcar #'(lambda (x) (delete n x)) l)))))
0

There are 0 best solutions below