Common Lisp:检查词法变量是否存在?

ste*_*tef 3 scope common-lisp

如何检测范围中是否绑定了词法变量?我基本上想要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.")))
Run Code Online (Sandbox Code Playgroud)

因此,boundp正确检查动态变量(和常量),并且正如hyperspec所说,不包括词法绑定.

但我找不到任何等价的boundp词汇绑定.那我该怎么检查呢?(如果没有任何可移植的话,SBCL的实现特定代码就可以了.)

Rai*_*wig 8

在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>
Run Code Online (Sandbox Code Playgroud)

没有办法取名,看它是否有词汇限制.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
Run Code Online (Sandbox Code Playgroud)