Skip to main content

array-in-bounds-p

array-in-bounds-p Function

Syntax:

array-in-bounds-p array &rest subscripts → generalized-boolean

Arguments and Values:

array—an array.

subscripts—a list of integers of length equal to the rank of the array.

generalized-boolean—a generalized boolean.

Description:

Returns true if the subscripts are all in bounds for array; otherwise returns false. (If array is a vector with a fill pointer , that fill pointer is ignored.)

Examples:

(setq a (make-array(7 11) :element-type ’string-char)) 
(array-in-bounds-p a 0 0) → true
(array-in-bounds-p a 6 10) → true
(array-in-bounds-p a 0 -1) → false
(array-in-bounds-p a 0 11) → false
(array-in-bounds-p a 7 0) → false

See Also:

array-dimensions

Notes:

(array-in-bounds-p array subscripts)

(and (not (some #’minusp (list subscripts)))

(every #’< (list subscripts) (array-dimensions array)))

Expanded Reference: array-in-bounds-p

Basic Usage

array-in-bounds-p checks whether the given subscripts are valid indices for the array. It returns true if all subscripts are in bounds, false otherwise.

(let ((v (make-array 5)))
(list (array-in-bounds-p v 0) ; first element
(array-in-bounds-p v 4) ; last element
(array-in-bounds-p v 5) ; out of bounds
(array-in-bounds-p v -1))) ; negative index
=> (T T NIL NIL)

Multi-Dimensional Arrays

For multi-dimensional arrays, provide one subscript per dimension.

(let ((m (make-array '(3 4))))
(list (array-in-bounds-p m 0 0) ; top-left corner
(array-in-bounds-p m 2 3) ; bottom-right corner
(array-in-bounds-p m 3 0) ; row out of bounds
(array-in-bounds-p m 0 4))) ; column out of bounds
=> (T T NIL NIL)

Fill Pointer Is Ignored

array-in-bounds-p checks against the actual array dimensions, not the fill pointer.

(let ((v (make-array 10 :fill-pointer 3)))
(list (array-in-bounds-p v 5) ; beyond fill pointer, but in bounds
(array-in-bounds-p v 9) ; last actual element
(array-in-bounds-p v 10))) ; truly out of bounds
=> (T T NIL)

Safe Array Access Pattern

Use array-in-bounds-p to guard against out-of-bounds errors.

(defun safe-aref (array &rest subscripts)
"Access an array element safely, returning NIL if out of bounds."
(when (apply #'array-in-bounds-p array subscripts)
(apply #'aref array subscripts)))

(let ((v (vector 10 20 30)))
(list (safe-aref v 1)
(safe-aref v 5)))
=> (20 NIL)