Elisp: Vector

By Xah Lee. Date: . Last updated: .

What is Vector

Emacs lisp vector datatype is a ordered sequence of values, with fixed number of elements. It implements the array data structure.

Create Vector

make-vector

(make-vector length value)

Create a vector of given length and value for all elements.

(make-vector 3 0)
;; [0 0 0]
vector

(vector a b etc)

Create a vector with elements, the elements are evaluated.

(let ((xx 3))
  (vector 1 2 xx))
;; [1 2 3]
[a b etc]

Create a vector, do not evaluate elements. Typically used when all elements are Number or String or Symbol .

;; vector of numbers
(setq xx [3 4 5])
;; [3 4 5]

;; vector of strings
(setq xx ["aa" "bb" "cc"])
;; ["aa" "bb" "cc"]

;; vector of symbols
(setq xx [aa bb cc])
;; [aa bb cc]

;; vector of numbers or strings or symbols
(setq xx [3 "aa" aa])
;; [3 "aa" aa]

Fill Vector

fillarray

(fillarray arrayVar value)

Make all elements of arrayVar to have value value, modify the arrayVar, return the variable's new value.

arrayVar can a variable of array, or just array. 〔see Elisp: Sequence Type

(setq xx [3 4 5])
;; [3 4 5]

(fillarray xx 1)
;; [1 1 1]

;; original changed
xx
;; [1 1 1]
(fillarray [3 4 5] 1)
;; [1 1 1]

Length

(length (vector 7 4 5))
;; 3

Get Element

aref

(aref array n)

Return the element of array at index n.

;; get a element from vector
(aref ["a" "b" "c"] 0)
;; "a"

Change Element

aset

(aset arrayVar idx new)

  • Change element of arrayVar at index idx the value new.
  • Modifies arrayVar.
  • Return new.
(setq xx [3 4 5])
;; [3 4 5]

(aset xx 0 "b")
;; "b"

xx
;; ["b" 4 5]

Nested Vector

Vector can be nested in any way, because the elements can be any type.

;; nested vector
[[1 2] [3 4]] ; 2 by 2 matrix
;; random nested vector
[8 [3 [2 9] c] 7 [4 "b"]]

Reference

Elisp, Vector

Elisp, Data Structure