我现在对符号感到困惑,我尝试过:
CL-USER> (defclass foo2 () ())
#<STANDARD-CLASS COMMON-LISP-USER::FOO2>
CL-USER> (describe 'foo2)
COMMON-LISP-USER::FOO2
[symbol]
FOO2 names the standard-class #<STANDARD-CLASS COMMON-LISP-USER::FOO2>:
Direct superclasses: STANDARD-OBJECT
No subclasses.
Not yet finalized.
No direct slots.
; No value
CL-USER> (find-symbol "foo2")
NIL
NIL
为什么我无法通过find-symbol
函数找到“ foo2”符号?
我想要做什么:
CL-USER> (defun my-make-instance (name n) (make-instance (make-symbol (format nil "~a-~a" name n)))
MY-MAKE-INSTANCE
CL-USER> (my-make-instance "foo" 2)
; Evaluation aborted on #<SB-PCL:CLASS-NOT-FOUND-ERROR foo2 {1003A3A003}>.
我得到:
There is no class named #:|foo2|.
我该怎么做?
以及其他情况:
CL-USER> (describe 'foo2)
COMMON-LISP-USER::FOO2
[symbol]
FOO2 names the standard-class #<STANDARD-CLASS COMMON-LISP-USER::FOO2>:
Direct superclasses: STANDARD-OBJECT
No subclasses.
Not yet finalized.
No direct slots.
; No value
CL-USER> (describe (intern "foo2"))
COMMON-LISP-USER::|foo2|
[symbol]
; No value
为什么发生? defclass创建的“ foo2”是内部符号吗?
make-symbol
的调用将返回一个新的符号对象,而不是与您的班级关联的符号对象。最简单的修复代码的方法是将对make-symbol
中的my-make-instance
调用替换为对read-from-string
的调用,以获取与转换要在参数字符串上使用的阅读器行为相同的大小写。然后,读者还将在当前包中实习该符号,以确保该符号与与您的班级关联的符号对象相同。在这种情况下,您可能还想使用defun
而不是defmacro
来定义my-make-instance
。简而言之,您可能需要以下代码:
(defun my-make-instance (name n)
(make-instance (read-from-string (format nil "~a-~a" name n))))
(defclass foo-2 () ())
(my-make-instance "foo" 2)
;returns below instance
#<FOO-2 {100AB67443}>