1

Q: how do I pop an arbitrary element from a list?

Given the list '(a b c d e), pop returns a and destructively modifies the list to '(b c d e). How can I generalize this function so I could pop an arbitrary element (say, c)?

I'm almost sure I've seen this in a library somewhere, but can't remember where.

  • An afterthought: maybe you were just thinking of delq? Do you want to delete by position or value (in the latter case you probably don't need the value returned). – ebpa Oct 19 '17 at 14:53
5

Simply (pop (nthcdr n my-list)):

(let ((x '(a b c d e)))
  (list (pop (nthcdr 2 x))
        x))
;; => (c (a b d e))
  • 2
    I think it's funny that I wrote a little function to setcar and setcdr of the nthcdr and was thinking of an appropriate name for the function and once I thought "pop-nthcdr" realized "oh! you could just write that!" </facepalm> – ebpa Oct 19 '17 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.