Article View: comp.lang.clos
Article #137Smart diplay method
From: Steve Haflich
Date: Wed, 16 Sep 1992 01:29
Date: Wed, 16 Sep 1992 01:29
44 lines
2375 bytes
2375 bytes
From: raman@cs.cornell.edu (T. V. Raman)
How do I write a print-object method for a class that neatly formats
slot names and values one per line without having to explicitly write
(format "..."
(<slot-name-value> object)
..
)
You should first consider the `contract' that a print-object method is
supposed to obey. The major purpose print-object exists is so the
printer can call it to deal with user-defined objects. Unless you can
guarantee that the method won't be called in the general case (for
instance, by specializing the method on the stream argument) then the
method shouldn't emit any newlines because that can screw up the
printer, and especially, the pretty printer, and cause them to
interact poorly with other tools in the implementation (debugger,
inspector, whatever) that rely on the behavior of the printer.
To write the code in a way that doesn't violate the contract, you need
to use the new pretty-printer directives described in CLtL2 chapter
27. These include pprint-logical-block, pprint-newline, pprint-tab,
and pprint-indent. You can use these either directly, or through the
format directive interface.
All this is pretty tricky if you haven't used the new printer before.
The easy part of the problem is getting your hands on the object's
slots, etc., assuming just a minimal amount of the MOP is available.
This is an approximation:
(defmethod print-object ((x foo) s)
(let* ((class (class-of x))
(slots (clos:class-slots class))
(l (mapcar #'(lambda (slot)
(let* ((name (clos:slot-definition-name slot))
(boundp (slot-boundp x name))
(val (and boundp
(slot-value x name))))
(list name boundp val)))
slots)))
(print-unreadable-object (x s :type t :identity nil)
(format s "~<~:@{~s: ~15:T~:[<unbound>~;~s~]~:@_~}~:>"
l))))
Technical Details
Message-ID:
<9209160129.AA13089@akbar.Franz.COM>Path:
arc1-ca.pugleaf.net!sparky!uunet!usc!sdd.hp.com!swrinde!zaphod.mps.ohio-state.edu!cis.ohio-state.edu!franz.com!smhReferences:
<1992Sep15.234132.10261@cs.cornell.edu>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!sparky!uunet!usc!sdd.hp.com!swrinde!zaphod.mps.ohio-state.edu!cis.ohio-state.edu!franz.com!smh From: smh@franz.com (Steve Haflich) Newsgroups: comp.lang.clos Subject: Smart diplay method Message-ID: <9209160129.AA13089@akbar.Franz.COM> Date: 16 Sep 92 01:29:39 GMT References: <1992Sep15.234132.10261@cs.cornell.edu> Sender: daemon@cis.ohio-state.edu Organization: The Ohio State University Department of Computer and Information Science Lines: 44