在 Common Lisp 中,如何覆盖 CLOS 类的默认字符串表示形式,以便对 format
或 princ
的调用将打印出可理解的内容,即使嵌入了该类的对象也是如此在其他类型中,例如列表或数组?
例如,如果我在 x 持有解决方案类的实例时调用 (format t "~a~%" x)
,我希望它打印类似 #
而不是 #
。
到目前为止,我设法弄清楚的是编写自定义函数来处理我知道将包含此类实例的打印结构,但这很乏味。 Lisp 确实提供了一些免费获得此功能的方法吗?
In Common Lisp, how can I override the default string representation of a CLOS class so that calls to format
or princ
will print something intelligible, even when objects of that class are embedded within other types, such as lists or arrays?
For example, if I call (format t "~a~%" x)
when x holds an instance of my solution class, I want it to print something like #<SOLUTION genes: #(1 2 3) scores: #(4 5) rank: 6>
instead of #<SOLUTION {BB7CD31}>
.
So far, all I have managed to figure out is writing custom functions to handle printing structures that I know will contain instances of this class, but this is tedious. Surely Lisp provides some way to get this functionality for free?
发布评论
评论(3)
您应该查看
print-object
和print-unreadable-object
。假设您有一个名为FOO
的类,如下所示:并且您想要打印如下实例:
#
where"xyz"< /code> 是插槽
name
的内容。在这种情况下,以下print-object
的实现将执行您想要的操作:You should be looking at
print-object
andprint-unreadable-object
. Suppose you have a class namedFOO
like so:And you want to print instances like this:
#<FOO "xyz">
where"xyz"
is the content of slotname
. In this case, the following implementation ofprint-object
would do what you want:查看
print-object< /代码>
。
Check out
print-object
.如果您还查看22.1.3.13 打印其他对象,它建议< a href="http://www.lispworks.com/documentation/lw51/CLHS/Body/m_pr_unr.htm#print-unread-object" rel="nofollow">print-unreadable-object 作为此类情况的通用格式宏
If you also look 22.1.3.13 Printing Other Objects it suggests print-unreadable-object as a common format macro for such situations