Skip to main content

vector-pop

vector-pop Function

Syntax:

vector-pop vector → element

Arguments and Values:

vector—a vector with a fill pointer .

element—an object.

Description:

Decreases the fill pointer of vector by one, and retrieves the element of vector that is designated by the new fill pointer .

Examples:

(vector-push (setq fable (list ’fable)) 
(setq fa (make-array 8
:fill-pointer 2
:initial-element ’sisyphus)))2
(fill-pointer fa)3
(eq (vector-pop fa) fable) → true
(vector-pop fa) → SISYPHUS
(fill-pointer fa)1

Side Effects:

The fill pointer is decreased by one.

Affected By:

The value of the fill pointer .

Exceptional Situations:

An error of type type-error is signaled if vector does not have a fill pointer .

If the fill pointer is zero, vector-pop signals an error of type error.

See Also:

vector-push, vector-push-extend, fill-pointer

Expanded Reference: vector-pop

Basic Usage

vector-pop decreases the fill pointer by one and returns the element that was at that position. It is the inverse of vector-push.

(let ((v (make-array 5 :fill-pointer 3
:initial-contents '(a b c nil nil))))
(list (vector-pop v) ; removes and returns C
(vector-pop v) ; removes and returns B
(fill-pointer v)
v))
=> (C B 1 #(A))

Stack-Like Behavior

vector-push and vector-pop together implement a stack (LIFO) on a vector.

(let ((stack (make-array 10 :fill-pointer 0)))
(vector-push 'first stack)
(vector-push 'second stack)
(vector-push 'third stack)
(list (vector-pop stack) ; LIFO: third comes out first
(vector-pop stack)
(vector-pop stack)))
=> (THIRD SECOND FIRST)

Error on Empty Vector

vector-pop signals an error if the fill pointer is zero (the vector is logically empty).

;; This would signal an error:
;; (vector-pop (make-array 5 :fill-pointer 0))
;; --> ERROR: fill pointer is zero

;; Safe usage -- check before popping
(let ((v (make-array 5 :fill-pointer 0)))
(if (> (fill-pointer v) 0)
(vector-pop v)
:empty))
=> :EMPTY

Push/Pop Cycle with vector-push-extend

Combining vector-push-extend and vector-pop for a dynamically-sized stack.

(let ((stack (make-array 2 :fill-pointer 0 :adjustable t)))
(dotimes (i 5)
(vector-push-extend (* i 10) stack))
(let ((results '()))
(dotimes (i 3)
(push (vector-pop stack) results))
(list :popped (nreverse results)
:remaining (copy-seq stack))))
=> (:POPPED (40 30 20) :REMAINING #(0 10))