0

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.

1 Answer 1

1

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:

  1. x only has 1 element. The result is NIL, and this can't be achieved by modifying the list in place.
  2. 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.
Sign up to request clarification or add additional context in comments.

12 Comments

Wouldn't just (delete y x) do it, too?
Not if y is the first element of x.
In CLISP try: (defvar x (list 1)) (delete 1 x) (print x)
@Gwang-JinKim "destructive" is not the same as "in-place". A function being defined as destructive simply means there's less guarantees about it (i.e. it's not safe to share structures). It does not mean more guarantees, i.e. that it could be used in-place.
I think he asks for something different. He would like to change the list, given only a pointer to an item, the 'nested list'.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.