Reputation: 17573
I'm wondering if it's possible to remove a nested list from a list, given a pointer to the nested list. E.g., suppose we say
(defvar y '(1 2 3))
(defvar x (list 4 5 y 6 7))
Now X is (4 5 (1 2 3) 6 7)
. Is there a way to use Y to modify X to (4 5 6 7)
?
(setf y nil)
doesn't modify X, so it doesn't have the expected effect. The closest I've gotten is
(rplacd y nil)
which modifies X to (4 5 (1) 6 7)
.
EDIT: In the problem I am hoping to solve, X is a large and messy (having pointers back into itself in various places). For this reason I would am motivated to try to avoid searching X to find Y and then removing Y. This, I believe, rules out DELETE.
SECOND EDIT: X must be modified in-place. This, too, rules out DELETE, since DELETE might or might not modify X in place.
Upvotes: 0
Views: 117
Reputation: 782064
Use delete
(setf x (delete y x))
While the specification says that delete
is allowed, but not required, to modify the list in place, it does modify in place in all implementations I'm aware of. However, you still have to assign the result back to the variable to handle some cases:
x
only has 1 element. The result is NIL
, and this can't be achieved by modifying the list in place.y
is the first element of x
. Many implementations of delete
work by changing the cdr of the previous element, and there's no previous element in this case. So deleting the first element works by returning the second cons.Upvotes: 1