Racket, access structure fields in function -


i have fold function want use on number of different structures, each structure arbitrarily named fields. thus, need tell fold function kind of structure passed it, , field access. need this:

(define-struct test (element)) (define test_struct (make-test 0))  (define (getfield elementname structure)   ((typeof structure)-elementname structure))  (getfield element test_struct) 

the last line equivalent to:

(test-element test_struct) 

of course none of above correct syntax, should display i'm going for. based on other questions here on stackoverflow, seems answer has syntax have no idea how works.

what won't work

although can introspect struct type @ run time, don't see how use in macro @ compile time. because @ compile time don't have give object-name except piece of syntax -- not live struct object type:

(require (for-syntax racket/syntax)) (define-syntax (get-field stx)   (syntax-case stx ()     [(_ field-name s)      (with-syntax ([id (format-id stx                                   "~a-~a"                                   (object-name #'s) ; um, yeah, won't work                                   #'field-name)])        #'(id s))])) 

what work instead?

  1. you have fold-ish function accept additional argument -- field accessor function. in example, test-element function accesses element field of test struct type.

    this similar how racket's sort has optional #:key extract-key argument, function apply each item value used sorting. example if sorting list of test structs, pass test-element accessor function.

    --or--

  2. you use dictionary instead of struct. equivalent of had above, using hasheq:

    (define test (hasheq 'element 0)) (hash-ref test 'element)  ; => 0 

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -