Elisp: Vector
What is Vector
Emacs lisp vector datatype is a ordered sequence of values, with fixed number of elements. It implements the array data structure.
- Vector is a ordered sequence of values.
- Any element can be any type, mixed.
- Element's value can be changed.
- Number of elements cannot change. (i.e. Vector's length is fixed.)
- Read/Write to any position has constant access time.
Create Vector
make-vector
-
(make-vector length val)
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 numbers or Symbols .
(setq xx [3 yy 5]) ;; [3 yy 5] (aref xx 1) ;; yy (symbolp (aref xx 1)) ;; t
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 Elisp: Sequence Type〕
(setq xx [3 4 5]) ;; [3 4 5] (fillarray xx 1) ;; [1 1 1] 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"]]