Created
February 27, 2013 18:16
-
-
Save takikawa/5050164 to your computer and use it in GitHub Desktop.
A hack to make struct access more terse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 ...))])) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> (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