This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

pop puzzle

3 posts · 1625 views

Hello Lispers!

It is usually said that (pop stack) is equivalent of (prog1 (first stack) (setf stack (rest stack))) or (let ((elt (first stack))) (setf stack (rest stack)) elt). I don't understand why the following function doesn't work as an equivalent of built-in pop:
(defun my-pop (lst)
  (let ((x (first lst)))
    (setf lst (rest lst))
    x))
Example:
? (setf lstA '(a b c))
? (my-pop lstB)
A
? lstA
(A B C)
? (setf lstB '(a b c))
? (pop lstB)
A
? lstB
(B C)
But:
? (setf lstC '(a b c))
? (let ((x (car lstC)))
    (setf lstC (cdr lstC))
    x)
A
? lstC
(B C)
:?:

Last edited by dynamic on , edited 1 time in total.

Re: pop puzzle

Your setf is modifying a local variable, not the original structure. There are ways of destructively modifying a list in-place (edit the car and cdr of the cons cells); but a lot of lisp code assumes cons cells are immutable (not enforceable in CL).

Read about defsetf and define-setf-expander. If you want to modify something in-place, macros are the way to go.

Re: pop puzzle

Thank you for your answer and pointers to defsetf and define-setf-expander. I will study it.