Emacs Lisp: Convert/Join List/Vector/String

By Xah Lee. Date: .

Join Vectors, List to Vector

(vconcat sequence1 sequence2 etc)
Join any sequence type and return a vector. (List and vector are both sequence types.)
;; join vectors
(equal
 (vconcat [3 4] ["a" "b"])
 [3 4 "a" "b"])

;; join vector and list
(equal
 (vconcat [3 4] '("a" "b"))
 [3 4 "a" "b"]
 )

;; join vector and string
(equal
 (vconcat [3 4] "ab")
 [3 4 97 98])

;; string elements are converted to char.
;; 97 is the codepoint for the char a

Sequence to List, Vector to List

(append sequence1 sequence2 etc)
Join any sequence type and return a list.

Warning: if you want result to be Proper List , the last element must be a list, or nil.

join lists:

;; join lists
(equal
 (list 1 2 3 4)
 (append (list 1 2) (list 3 4)))

convert vector to list:

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

;; this creates improper list
(equal
 (append [1 2 3] [4 5])
 '(1 2 3 . [4 5]))

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

;; join vectors and lists to list
(equal
 (append [1 2 3] [4 5] '(6))
 '(1 2 3 4 5 6))
;; proper list

Sequence to String

To convert a list to string, use mapconcat or format. [see Emacs Lisp: Format String]

mapconcat
(mapconcat function sequence separator)

Apply function to each element, and concat the results as strings, with separator between elements.

;; list to string
(string-equal
 (mapconcat 'number-to-string '(1 2 3) ",")
 "1,2,3")
;; list to string
(string-equal
 (mapconcat 'identity '("a" "b" "c") ",")
 "a,b,c")
;; vector to string
(string-equal
 (mapconcat 'number-to-string [1 2 3] ",")
 "1,2,3")
(format "%s" sequence)
Return a string.
;; convert list to string

(format "%s" '(1 "two" 3))
;; "(1 two 3)"

(substring (format "%s" '(1 "two" 3)) 1 -1)
;; "1 two 3"

Lisp Basics

Lisp Data Structure


Lisp Basics

Basics

Lisp Data Structure

Function

Lisp Symbol

Lisp Misc

Working with Elisp