[plt-scheme] struct introspection

From: Jay McCarthy (jay.mccarthy at gmail.com)
Date: Tue May 25 17:48:49 EDT 2010

This program demonstrates some of your options:

#lang racket
(require (for-syntax racket/struct-info))

(define-struct blah (a b c)

(define-syntax (static-get-fields stx)
  (syntax-case stx ()
    [(_ struct)
     (let ([v (extract-struct-info (syntax-local-value #'struct))])
       (quasisyntax/loc stx
         (printf "~s\n" '#,v)))]))

(define (dynamic-get-fields v)
  (define-values (st skipped?) (struct-info v))
  (define-values (name fields auto acc mut imm super sti-skipped?)
(struct-type-info st))
  (printf "~s\n" (list name fields)))

(static-get-fields blah)
(dynamic-get-fields (blah 1 2 3))

It prints:

(struct:blah make-blah blah? (blah-c blah-b blah-a) (#f #f #f) #t)
(blah 3)

As you can see, statically you can find out the names of the
accessors, but dynamically you can only find out how many fields there

Since someone can write:

(define-struct funny-struct (funny-field) #:transparent)

You can't reliably recover "field names" even though you can get the accessors.


On Tue, May 25, 2010 at 3:38 PM, Todd O'Bryan <toddobryan at gmail.com> wrote:
> I feel like I've asked this before, but can't find it anywhere.
> If I
> (define-struct blah (a b c)
>  #:transparent)
> is there any way to get the names of blah's fields?
> Todd
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme

Jay McCarthy <jay at cs.byu.edu>
Assistant Professor / Brigham Young University

"The glory of God is Intelligence" - D&C 93

Posted on the users mailing list.