scope - 普通 Lisp : check if lexical variable exists?

标签 scope common-lisp

如何检测词法变量是否绑定(bind)在范围内?我基本上想要boundp对于词法变量。

具体来说,说我有:

(defvar *dynamic* 1)
(defconstant +constant+ 2)

(let ((lexical 3))
  (when (boundp '*dynamic*)  ; t
    (print "*dynamic* bound."))
  (when (boundp '+constant+) ; t
    (print "+constant+ bound."))
  (when (boundp 'lexical)    ; nil
    (print "lexical bound.")))

所以boundp正确检查动态变量(和常量)和as the hyperspec says , 不包括词法绑定(bind)。

但我找不到任何等效的 boundp用于词法绑定(bind)。那么我该如何检查它们呢? (如果没有任何可移植的东西,那么 SBCL 的实现特定代码就可以了。)

最佳答案

在 ANSI Common Lisp 中没有类似的东西。无法访问词汇环境。

你只能这样检查:

CL-USER 8 > (let ((lexical 3))
              (when (ignore-errors lexical) 
                (print "lexical bound."))
              (values))

"lexical bound." 

CL-USER 9 > (let ((lexical 3))
              (when (ignore-errors lexxxical) 
                (print "lexical bound."))
              (values))
<nothing>

没有办法取一个名字,看看它是否在词法上是完全绑定(bind)的。 CL 有一个扩展,其中函数 variable-information会提供一些信息,但即使在这种情况下它也可能不起作用:
* (require "sb-cltl2")

("SB-CLTL2")
* (apropos "variable-information")

VARIABLE-INFORMATION
SB-CLTL2:VARIABLE-INFORMATION (fbound)
* (let ((lexical 3))
     (sb-cltl2:variable-information 'lexical))
; in: LET ((LEXICAL 3))
;     (LET ((LEXICAL 3))
;       (SB-CLTL2:VARIABLE-INFORMATION 'LEXICAL))
; 
; caught STYLE-WARNING:
;   The variable LEXICAL is defined but never used.
; 
; compilation unit finished
;   caught 1 STYLE-WARNING condition

NIL
NIL
NIL

关于scope - 普通 Lisp : check if lexical variable exists?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643841/

相关文章:

c++ - 有条件地实例化一个具有已删除的默认构造函数的类

JavaScript addEventListener 与事件和绑定(bind)变量

c++ - 创建新结构、插入列表、重新使用指针、在 vector 中返回……是否以及如何删除?

lisp - 为什么这两个打印相同的东西?

vector - sbcl 中位向量使用多少内存?

macros - Common Lisp 宏中的词法绑定(bind)

c - 为什么我的 printfs 给出不同的值?

pointers - 通用 Lisp CFFI : pointer to the pointer

syntax-error - Lisp - 替换列表中元素的所有外观

javascript - 如何从函数内部获取变量?