pop
pop Macro
Syntax:
pop place → element
Arguments and Values:
place—a place, the value of which is a list (possibly, but necessarily, a dotted list or circular list). element—an object (the car of the contents of place).
Description:
pop reads the value of place, remembers the car of the list which was retrieved, writes the cdr of the list back into the place, and finally yields the car of the originally retrieved list.
For information about the evaluation of subforms of place, see Section 5.1.1.1 (Evaluation of Subforms to Places).
Examples:
(setq stack ’(a b c)) → (A B C)
(pop stack) → A
stack → (B C)
(setq llst ’((1 2 3 4))) → ((1 2 3 4))
(pop (car llst)) → 1
llst → ((2 3 4))
Side Effects:
The contents of place are modified.
See Also:
push, pushnew, Section 5.1 (Generalized Reference)
Notes:
The effect of (pop place) is roughly equivalent to
(prog1 (car place) (setf place (cdr place)))
except that the latter would evaluate any subforms of place three times, while pop evaluates them only once.
Expanded Reference: pop
Removing and returning the first element
pop reads the first element from the list stored in a place, updates the place to the rest of the list, and returns the removed element.
(let ((stack '(a b c)))
(values (pop stack) stack))
=> A
=> (B C)
Using push and pop as a stack
push and pop together implement a LIFO (last-in, first-out) stack.
(let ((stack nil))
(push 1 stack)
(push 2 stack)
(push 3 stack)
(list (pop stack)
(pop stack)
(pop stack)))
=> (3 2 1)
pop on the empty list
Popping from an empty list (NIL) returns NIL and leaves the place as NIL.
(let ((lst nil))
(values (pop lst) lst))
=> NIL
=> NIL
pop with generalized places
pop works with any setf-able place, not just simple variables.
(let ((data (list '(1 2 3))))
(values (pop (car data)) data))
=> 1
=> ((2 3))
Processing a list element by element with pop
pop provides a concise way to consume a list in a loop.
(let ((lst '(10 20 30))
(sum 0))
(loop while lst do (incf sum (pop lst)))
sum)
=> 60