10.3 反引用(DONE)

反引用允许你引用一个列表,并可以控制列表的哪些部分求值,哪些不被求值。在某些情况下,反引用和特殊表达式 quote 完全等同。举个例子,下面两个表达式会生成完全等价的结果:

`(a list of (+ 2 3) elements)
     ⇒ (a list of (+ 2 3) elements)
'(a list of (+ 2 3) elements)
     ⇒ (a list of (+ 2 3) elements)

特殊记号',',用在反引用中,用于标记哪些位置需要求值,而不是作为常量对待。Emacs Lisp 求值器会对有逗号标记的参数求值,并将求值结果放在原先的列表结构中:

`(a list of ,(+ 2 3) elements)
     ⇒ (a list of 5 elements)

','同样支持深层嵌套列表结构,例如:

`(1 2 (3 ,(+ 4 5)))
     ⇒ (1 2 (3 9))

你还可以将求值的结果拼接到列表中,并作为结果返回,此时你需要使用特殊符号',@',这个符号会将列表内的元素作为外层列表的元素,拼接到同等层级。而等价的,不使用反引号的写法往往不具备可读性。这里有一些例子:

(setq some-list '(2 3))
     ⇒ (2 3)
(cons 1 (append some-list '(4) some-list))
     ⇒ (1 2 3 4 2 3)
`(1 ,@some-list 4 ,@some-list)
     ⇒ (1 2 3 4 2 3)

(setq list '(hack foo bar))
     ⇒ (hack foo bar)
(cons 'use
  (cons 'the
    (cons 'words (append (cdr list) '(as elements)))))
     ⇒ (use the words foo bar as elements)
`(use the words ,@(cdr list) as elements)
     ⇒ (use the words foo bar as elements)

如果反引用结果中没有替换和拼接,那么它表现起来和 quote 很像,同样生成点对,向量,字符串这些不可变对象。

最后更新于