Created
September 20, 2012 23:59
-
-
Save dyoo/3759037 to your computer and use it in GitHub Desktop.
Records - like structs but less ugly and much less efficient
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 rackunit | |
(for-syntax racket/syntax)) | |
;Records - like structs but less ugly and much less efficient | |
(define-syntax (record stx) | |
(syntax-case stx () | |
[(_ name slots ...) | |
(with-syntax ([new-name (format-id #'name "new-~a" (syntax-e #'name))]) | |
(quasisyntax/loc stx | |
(begin | |
(define-struct/derived #,stx name (ht) | |
#:property prop:procedure (lambda (self key) | |
(match self | |
[(struct name (ht)) | |
(hash-ref ht key)]))) | |
(define (new-name . values) | |
(let ([ht (make-hash (map cons '(slots ...) values))]) | |
(name ht))))))])) | |
(record pos x y) | |
(define p (new-pos 1 2)) | |
(check-equal? (p 'x) 1) | |
(pos? p) | |
(pos? 42) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: See http://racket-lang.org/irc-logs/20120920.txt at around 19:37.