Emacs Lisp: Vector

By Xah Lee. Date: . Last updated: .

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 val)

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

(equal
 (make-vector 5 0)
 [0 0 0 0 0]
 )
vector
(vector a b etc)

Create a vector with elements, the elements are evaluated.

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

Create a vector, do not evaluate elements.

(let (aa xx)
  (setq aa 4
        xx [3 aa 5])
  (equal
   'aa
   (aref xx 1)))
;; t
;; the aa remains a symbol

Fill Vector

fillarray
(fillarray arrayVar val)

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

arrayVar can a variable of array, or just array. [see Emacs Lisp: Sequence Type]

(setq xx [3 4 5])

(eq
 ;; set all element to 1, modify the variable, return the var's new value
 (fillarray xx 1)
 xx
 )

(equal xx [1 1 1] )
(equal
 (fillarray [3 4 5] 1)
 [1 1 1])

Length

(equal
 (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
(equal
 (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])
(equal (aset xx 0 "b") "b")
(equal 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"]]

Convert/Join Sequence/List/Vector/String

Transpose Matrix

Reference

Lisp Data Structure

List

Specialized Lists

Vector

Sequence (List, Vector)

Hash Table