Skip to content

Instantly share code, notes, and snippets.

@dyoo
Created September 20, 2012 23:59
Show Gist options
  • Save dyoo/3759037 to your computer and use it in GitHub Desktop.
Save dyoo/3759037 to your computer and use it in GitHub Desktop.
Records - like structs but less ugly and much less efficient
#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)
@dyoo
Copy link
Author

dyoo commented Sep 29, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment