Lisp:如何覆盖 CLOS 类的默认字符串表示形式?

发布于 2024-12-03 19:33:04 字数 438 浏览 3 评论 0 原文

在 Common Lisp 中,如何覆盖 CLOS 类的默认字符串表示形式,以便对 formatprinc 的调用将打印出可理解的内容,即使嵌入了该类的对象也是如此在其他类型中,例如列表或数组?

例如,如果我在 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蔚蓝源自深海 2024-12-10 19:33:04

您应该查看 print-objectprint-unreadable-object。假设您有一个名为 FOO 的类,如下所示:

(defclass foo ()
  ((name :accessor foo-name)))

并且您想要打印如下实例: # where "xyz"< /code> 是插槽name 的内容。在这种情况下,以下 print-object 的实现将执行您想要的操作:

(defmethod print-object ((obj foo) out)
  (print-unreadable-object (obj out :type t)
    (format out "~s" (foo-name obj))))

You should be looking at print-object and print-unreadable-object. Suppose you have a class named FOO like so:

(defclass foo ()
  ((name :accessor foo-name)))

And you want to print instances like this: #<FOO "xyz"> where "xyz" is the content of slot name. In this case, the following implementation of print-object would do what you want:

(defmethod print-object ((obj foo) out)
  (print-unreadable-object (obj out :type t)
    (format out "~s" (foo-name obj))))
风吹过旳痕迹 2024-12-10 19:33:04

如果您还查看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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文