gpt4 book ai didi

common-lisp - Common Lisp 中 &environment 的作用是什么?

转载 作者:行者123 更新时间:2023-12-04 14:12:56 30 4
gpt4 key购买 nike

我对常见的 lisp 中的 &environment 参数感到困惑。特别是它有什么用,为什么它是一个参数,而不是一个特殊的变量?

编辑:也很高兴看到 &environment 的具体示例。将在代码中使用。

最佳答案

文档

Macro Lambda Lists :

&environment is followed by a single variable that is bound to an environment representing the lexical environment in which the macro call is to be interpreted. This environment should be used with macro-function, get-setf-expansion, compiler-macro-function, and macroexpand (for example) in computing the expansion of the macro, to ensure that any lexical bindings or definitions established in the compilation environment are taken into account.



解释

定义宏(本地或全局)的运算符必须在评估或编译之前定义代码如何扩展,因此可能需要扩展现有宏,其扩展可能取决于环境 - 因此宏定义需要环境。

不是特殊变量

特殊变量更危险,因为用户可能会重新绑定(bind)它们并且因为它们更难在多线程代码中正确处理。

例子

遍布 places.lisp :
(defmacro psetf (&whole whole-form
&rest args &environment env)
(labels ((recurse (args)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion (car args) env)
(declare (ignore getterform))
(when (atom (cdr args))
(error-of-type 'source-program-error
:form whole-form
:detail whole-form
(TEXT "~S called with an odd number of arguments: ~S")
'psetf whole-form))
(wrap-let* (mapcar #'list temps subforms)
`(MULTIPLE-VALUE-BIND ,stores ,(second args)
,@(when (cddr args) (list (recurse (cddr args))))
,@(devalue-form setterform))))))
(when args `(,@(recurse args) NIL))))

来自 iolib/src/new-cl/definitions.lisp :
(defmacro defconstant (name value &optional documentation
&environment env)
(destructuring-bind (name &key (test ''eql))
(alexandria:ensure-list name)
(macroexpand-1
`(alexandria:define-constant ,name ,value
:test ,test
,@(when documentation `(:documentation ,documentation)))
env)))

关于common-lisp - Common Lisp 中 &environment 的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23944846/

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