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?
you have
fold-ish function accept additional argument -- field accessor function. in example,test-elementfunction accesseselementfield ofteststruct type.this similar how racket's
sorthas optional#:key extract-keyargument, function apply each item value used sorting. example if sorting list ofteststructs, passtest-elementaccessor function.--or--
you use dictionary instead of struct. equivalent of had above, using
hasheq:(define test (hasheq 'element 0)) (hash-ref test 'element) ; => 0
Comments
Post a Comment