Emacs Lisp: Backquote Reader Macro for List

By Xah Lee. Date: .

Backquote Reader Macro is a lisp reader macro , which transforms syntax before lisp compiler runs the code.

Backquote Reader Macro is useful for:

Eval Some Elements Only

Syntax:

`(x1 x2 rest)

for each element you want to eval, put a comma in front of it. e.g. eval second elemnt

`(x1 ,x2 x3)

;; example of eval only some element of a list

(setq x1 1)
(setq x2 2)

;; eval just x1
(setq x3 `(0 ,x1 x2))

(equal
 x3
 '(0 1 x2))
;; true

(proper-list-p x3)
;; true

Change List into Its Elements

Syntax:

`(x1 x2 rest)

for each element that is a list you want to become elements, put “comma at” ,@ in front of it. e.g. spill x2 as elements:

`(x1 ,@x2 x3)

;; example of turning a list into elements, inside a list

(setq x1 (list 1 2))
(setq x2 (list 3 4))

;; we want the elements of x1 and x2 inside a list, but not as sublist
(setq x3 `(0 ,@ x1 ,@ x2))

(equal
 x3
 '(0 1 2 3 4))
;; true

(proper-list-p x3)
;; true
;; Backquote Reader Macro can be used to feed a list into a function as args

;; our test function
(defun ff (x y z)
  "return args as one string"
  (format "%s %s %s"  x y z))

;; normal usage
(equal
 (ff 2 3 4)
 "2 3 4")

;; define a list
(setq xx '(2 3 4))

;; use backquote reader macro, to turn a list into elements, then use eval
(equal
 (eval `(ff ,@ xx))
 "2 3 4")

Lisp Data Structure

List

Specialized Lists

Vector

Sequence (List, Vector)

Hash Table