0

I sometimes find it useful to be able to take a struct object and see its slots and values. But if I evaluate a struct object I only see its values, not the names of the slots. E.g. if I have a struct like:

(cl-defstruct apple type color price)

(setq my-apple (make-apple :type "granny smith" :color "green" :price 2))

and I evaluate my-apple, I get the printed representation of the record: #s(apple "granny smith" "green" 2).

I've written a function that takes any struct-object and outputs a list of the slots and values:

(defun my/print-struct (struct)
  (let* ((struct-type (aref struct 0))
         (slots (cdr (mapcar 'car (cl-struct-slot-info struct-type)))))
    (cl-loop for slot in slots
             collect (let* ((struct-type-name (symbol-name struct-type))
                            (slot-name (symbol-name slot))
                            (slot-getter (intern (format "%s-%s"
                                                         struct-type-name
                                                         slot-name))))
                       `(,slot ,(funcall slot-getter struct))))))

(my/print-struct my-apple) returns ((type "granny smith") (color "green") (price 2)).

All this is fine for my purposes, but it seems very hacky. How can I improve it?

Drew
  • 75,699
  • 9
  • 109
  • 225
Alan
  • 3
  • 3
  • https://emacs.stackexchange.com/tags/elisp/info – Drew Jun 23 '23 at 14:22
  • 1
    1. Please don't ask what is the best way to do something. 2. In this case, the question is unclear, since you don't provide any details about what kind of code improvement you're looking for. This isn't a discussion site; it's Q&A. Please post specific how-to or understanding questions, not here's-my-code-what-can-you-suggest-to-as-possible-improvements. – Drew Jun 23 '23 at 14:25
  • Apologies---I should have clarified that I was wondering if there was a canonical way to print a representation of a struct along the lines of defstructs in common lisp. – Alan Jun 23 '23 at 15:30
  • Put all clarification into the question itself. Comments can be deleted at any time. And please specify what you mean (are looking for) by "canonical way" - it's not clear what you're asking/requesting. – Drew Jun 23 '23 at 17:10

0 Answers0