Emacs Lisp: Vector

By Xah Lee. Date: . Last updated: .

Emacs lisp has a vector datatype. It is similar to Java's Array.

Emacs lisp vector:

  1. Reading/Writing a element has constant random access time.
  2. Elements can be any type.
  3. Elements cannot be added or removed. (that is, vector's length is fixed.)
  4. Element's value can be changed.

(info "(elisp) Vectors")

Create Vector

To create a vector, write it like this (vector a b …).

;; create a vector and set to var v
(setq v (vector 3 4 5))
(setq x 7)

;; each element will be evaluated
(setq v (vector 3 x 5))

v ; [3 7 5]

If you do not want the elements evaluated, write it like this: [a b …].

(setq x 7)

;; create a vector of elements 3 x 5
;; each element is NOT be evaluated
(setq v [3 x 5])

v ; [3 x 5] . the x remains a symbol, not 7

Length

(length (vector 7 4 5)) ; 3

Get Element

(aref array n) → Return the element of array at index n.

(elt sequence n) → Return element of sequence at index n.

When emacs doc mentions “SEQUENCE”, you can think of it as “list or vector”.

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

What's the difference between aref and elt?

elt is more general. It works on vector and list.

Change Element

(aset ARRAY IDX NEWELT) → Store into the element of ARRAY at index IDX the value NEWELT. Return NEWELT.

(setq v [3 4 5])
(aset v 0 "b")
v  ; ⇒ ["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"]]

Join Vectors, Convert List to Vector

(vconcat sequence1 sequence2 …) → join any sequence types and return a vector. (List and vector are both sequence types.)

;; join any sequence types
(vconcat [3 4] ["a" "b"]) ; ⇒ [3 4 "a" "b"]

(vconcat [3 4] '("a" "b")) ; ⇒ [3 4 "a" "b"]

(vconcat [3 4] "ab") ; ⇒ [3 4 97 98]
;; string elements are converted to char.
;; 97 is the codepoint for the char a

Convert Vector to List

(append sequence1 sequence2 …) → join any sequence types and return a list. (List and vector are both sequence types.)

Warning: if you want it to return a propert list, the last element must be a list, or nil.

;; convert vector to list
(append [1 2 3] nil)
; ⇒ (1 2 3)

(append [1 2 3] [4 5] )
;; (1 2 3 . [4 5])
;; this is improper list

(append [1 2 3] [4 5] nil)
;; (1 2 3 4 5)
;; proper list

(append [1 2 3] [4 5] '(6))
;; (1 2 3 4 5 6)
;; proper list

Map / Loop Thru Vector

Emacs Lisp: Map / Loop Thru List / Vector

(info "(elisp) Vector Functions")

Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs