Function that deletes all the elements of a list in common lisp?

Viewed 279

How can I create a function that deletes all the element of a given list?

Is there a function that already does it, or should I create it? I thought to use recursion to delete the first element until the list is empty

I need not just to be shown but to be deleted, for example when I have a list called list1 defined as ((a 2) (b 3) (c 4)), I need a function that deletes it so I can fill it later with other elements.

1 Answers

This sounds like a confusion: Lisp isn't like C where you have to manually manage storage. In case it isn't here are some possibilities.

If you want to 'delete' all the elements, then there's no purpose in doing that: simply stop referring to the list and they're gone. If the list is bound to some variable then, if there are no other references to it, it's gone when the variable goes out of scope. Alternatively just (setf var-bound-to-list nil) for instance (but don't do that if the variable is going to go out of scope anyway).

If you want to delete some of the elements then you probably want one of the remove or delete functions:

  • (remove elt sequence) will nondestructively remove elt from sequence: it will return a new sequence from which elt has been removed.
  • (delete elt sequence) is like remove except it is destructive: it will (almost always) destructively modify sequence.

Note that in the case of a list there is one case where delete is not destrctive: if elt is the first element of the list (if you think about how lists work the reason for this should be obvious). So you generally want to do (setf myvar (delete 'foo myvar)) to deal with that case.

Related