gpt4 book ai didi

macros - 为什么在这个宏定义中需要@符号?

转载 作者:太空宇宙 更新时间:2023-11-03 18:34:40 26 4
gpt4 key购买 nike

在下面的 when 宏中:

(defmacro when (condition &rest body)
`(if ,condition (progn ,@body)))

为什么有一个“at”@ 符号?

最佳答案

在准引用部分插入计算值时,有两个运算符:

  • “逗号”运算符,
  • “逗号拼接”运算符,@

Comma , 在准引用的 sexpr 中插入以下表达式的值,comma-splice 相反要求以下表达式是一个列表并且只能在准引用列表中使用:效果是在运算符出现的位置插入准引号列表中表达式的所有元素。

做个小实验很容易看出区别

> (let ((x '(1 2 3 4))) `(this is an example ,x of expansion))
(THIS IS AN EXAMPLE (1 2 3 4) OF EXPANSION)

> (let ((x '(1 2 3 4))) `(this is an example ,@x of expansion))
(THIS IS AN EXAMPLE 1 2 3 4 OF EXPANSION)

如您所见,使用 ,@ 会将列表的元素直接放在扩展中。如果没有,你会得到放在扩展中的列表。

,@ 与不产生列表的表达式一起使用将在执行替换时出错:

* (defun f (x) `(here ,@x we go))
F
* (f '(1 2 3))
(HERE 1 2 3 WE GO)
* (f '99)

debugger invoked on a TYPE-ERROR in thread
#<THREAD "main thread" RUNNING {10009F80D3}>:
The value
99
is not of type
LIST
when binding SB-IMPL::X

Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.

restarts (invokable by number or by possibly-abbreviated name):
0: [ABORT] Exit debugger, returning to top level.

(SB-IMPL::APPEND2 99 (WE GO)) [external]
0]

在分析准引用部分时,使用不在列表内的 ,@ 是错误的:

* (defun g (x) `,@x)

debugger invoked on a SB-INT:SIMPLE-READER-ERROR in thread
#<THREAD "main thread" RUNNING {10009F80D3}>:
`,@X is not a well-formed backquote expression

Stream: #<SYNONYM-STREAM :SYMBOL SB-SYS:*STDIN* {10000279E3}>

Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.

restarts (invokable by number or by possibly-abbreviated name):
0: [ABORT] Exit debugger, returning to top level.

(SB-IMPL::BACKQUOTE-CHARMACRO #<SYNONYM-STREAM :SYMBOL SB-SYS:*STDIN* {10000279E3}> #<unused argument>)
0]

关于macros - 为什么在这个宏定义中需要@符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5661875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com