Skip to content

Instantly share code, notes, and snippets.

@takikawa
Created February 27, 2013 18:16
Show Gist options
  • Save takikawa/5050164 to your computer and use it in GitHub Desktop.
Save takikawa/5050164 to your computer and use it in GitHub Desktop.
A hack to make struct access more terse
#lang racket
(require (for-syntax syntax/parse racket/syntax))
(define-values (prop:indexable indexable? indexable-accessor)
(make-struct-type-property 'indexable))
(define-syntax (% stx)
(syntax-parse stx
[(_ thing index)
#'((dict-ref (force (indexable-accessor thing)) (quote index))
thing)]))
(define-syntax (istruct stx)
(syntax-parse stx
[(_ name (field ...) other ...)
(with-syntax ([(accessor ...)
(map (λ (f) (format-id stx "~a-~a" #'name f))
(syntax->list #'(field ...)))])
#`(struct name (field ...)
#:property prop:indexable
(delay (make-hash `((field . ,accessor) ...)))
other ...))]))
> (istruct foo (x y))
> (define a-foo (foo 3 2))
> (% a-foo y)
2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment