print-method 函数行为异常
print-method function behaves weirdly
我在尝试自定义 CLOS 对象的 print-object
函数时遇到了一些奇怪的行为。该函数确实生成了预期的字符串,但它出现在对象定义之外(即 <OBJECT-NAME >
后跟 >
字符后我想要的字符串)。下面的框架代码重现了这个问题:
(defclass object () ;;; Define some object...
((element-count
:initarg :element-count
:accessor n)
(first-element
:initform nil
:accessor 1st)
(last-element
:initform nil
:accessor end)))
(defmethod print-object ((obj object) stream) ;;; ...and then its print-object method
(print-unreadable-object (obj stream :type t))
(with-accessors ((first 1st)
(last end)
(n n))
obj
(format stream " ~[empty~:;:elements ~:*~d :content ~:*(~[~;~a~;~a ~a~:;~a ... ~a~])~]"
n first last)))
输出字符串如下:
(defvar o1 (make-instance 'object :element-count 0)) => #<OBJECT > empty
(defvar o2 (make-instance 'object :element-count 1)) => #<OBJECT > :elements 1 :content (NIL)
(defvar o3 (make-instance 'object :element-count 2)) => #<OBJECT > :elements 2 :content (NIL NIL)
(defvar o4 (make-instance 'object :element-count 10)) => #<OBJECT > :elements 10 :content (NIL ... NIL)
我不明白这个输出。根据文档,在 space 之外打印不应该发生。还是应该?好吧,交给你了!顺便说一句,我在 Windows.
的 Portacle 上使用 SBCL
你放错了括号 - print-unreadable-object
creates an environment which should encompass the whole print-object
正文:
(defclass airplane () ((tail-number :initarg tail :accessor plane-tail)))
(defmethod print-object ((plane airplane) stream)
(print-unreadable-object (plane stream :type t)
(princ (plane-tail plane) stream)))
(make-instance 'airplane 'tail 1234)
==> #<AIRPLANE 1234>
我在尝试自定义 CLOS 对象的 print-object
函数时遇到了一些奇怪的行为。该函数确实生成了预期的字符串,但它出现在对象定义之外(即 <OBJECT-NAME >
后跟 >
字符后我想要的字符串)。下面的框架代码重现了这个问题:
(defclass object () ;;; Define some object...
((element-count
:initarg :element-count
:accessor n)
(first-element
:initform nil
:accessor 1st)
(last-element
:initform nil
:accessor end)))
(defmethod print-object ((obj object) stream) ;;; ...and then its print-object method
(print-unreadable-object (obj stream :type t))
(with-accessors ((first 1st)
(last end)
(n n))
obj
(format stream " ~[empty~:;:elements ~:*~d :content ~:*(~[~;~a~;~a ~a~:;~a ... ~a~])~]"
n first last)))
输出字符串如下:
(defvar o1 (make-instance 'object :element-count 0)) => #<OBJECT > empty
(defvar o2 (make-instance 'object :element-count 1)) => #<OBJECT > :elements 1 :content (NIL)
(defvar o3 (make-instance 'object :element-count 2)) => #<OBJECT > :elements 2 :content (NIL NIL)
(defvar o4 (make-instance 'object :element-count 10)) => #<OBJECT > :elements 10 :content (NIL ... NIL)
我不明白这个输出。根据文档,在 space 之外打印不应该发生。还是应该?好吧,交给你了!顺便说一句,我在 Windows.
的 Portacle 上使用 SBCL你放错了括号 - print-unreadable-object
creates an environment which should encompass the whole print-object
正文:
(defclass airplane () ((tail-number :initarg tail :accessor plane-tail)))
(defmethod print-object ((plane airplane) stream)
(print-unreadable-object (plane stream :type t)
(princ (plane-tail plane) stream)))
(make-instance 'airplane 'tail 1234)
==> #<AIRPLANE 1234>