home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!spool.mu.edu!yale.edu!qt.cs.utexas.edu!cs.utexas.edu!gateway
- From: gadbois@mcc.com (David Gadbois)
- Newsgroups: comp.lang.lisp
- Subject: Re: Function to print in #S format
- Date: 8 Sep 1992 19:40:34 -0500
- Organization: UTexas Mail-to-News Gateway
- Lines: 47
- Sender: daemon@cs.utexas.edu
- Message-ID: <19920909004003.1.GADBOIS@CLIO.MCC.COM>
- References: <SJAMESON.92Sep8161926@fergie.dnet.ge.com>
- NNTP-Posting-Host: cs.utexas.edu
-
- Date: Tue, 8 Sep 1992 15:19 CDT
- From: sjameson@fergie.dnet.ge.com (Stephen M Jameson)
-
- This ought to be a FAQ, but I haven't seen it. How do I print a
- structure in #S-format, i.e. so that the reader will automatically
- reconstruct the structure? The application is obvious: I would like
- to have a :PRINT-FUNCTION specified in the DEFSTRUCT which will
- print in a concise, non-readable format if a certain switch is set,
- and print in the verbose, readable format if the switch is not set.
- On the Symbolics I figured out a way to do it but it did not seem
- portable, and CLTL2 doesn't mention anything beyond the semantics of
- #S format, and that if you don't specify a :PRINT-FUNCTION, "a
- function is provided for the structure which will print out all its
- slots using #S syntax."
-
- If you have CLOS hooked in, you can define a method on PRINT-OBJECT that
- checks your switch (which probably should be just *PRINT-READABLY*) and
- calls CALL-NEXT-METHOD if it is not set. I do this so often I have
- written a macro to deal with it:
-
- (defmacro define-print-method ((object-var object-type stream-var) &body body)
- `(defmethod print-object ((,object-var ,object-type) ,stream-var)
- (if *print-readably*
- #+Genera
- ;; The default structure printer checks this and calls
- ;; PRINT-UNREADABLE-OBJECT if it is not set.
- (let ((scl:*print-structure-contents* t))
- (call-next-method))
- #-Genera
- (call-next-method)
- (print-unreadable-object (,object-var ,stream-var :type t)
- ,@body))))
-
- Note that CMU CL v15 did not let you use structure types as
- specializers, so this will not work there. I have not checked v16 yet
- to see if they have fixed it. For Lucid 4.0.x, you have to define
- *PRINT-READABLY* and PRINT-UNREADABLE-OBJECT yourself. At least Allegro
- and MCL get it right without extra kludgery. I sure will be happy when
- the draft proposed CL standard gets accepted so I'll never have to worry
- about portability problems again :-).
-
- If you do not have CLOS, you can always how the structure's print
- function do the #S printing by hand, but that is pretty gross. Or you
- could use implementation dependent accessors to get at the slot names
- and values (this is in the FAQ) and write a general printer.
-
- --David Gadbois
-