Skip to content

Instantly share code, notes, and snippets.

@Bogdanp
Created March 17, 2020 11:05
Show Gist options
  • Save Bogdanp/856b98edb6d4525787f30253132cf565 to your computer and use it in GitHub Desktop.
Save Bogdanp/856b98edb6d4525787f30253132cf565 to your computer and use it in GitHub Desktop.
#lang racket/base
(require (for-syntax racket/base
racket/format
syntax/parse
syntax/parse/class/struct-id))
(struct person (name age)
#:transparent)
(define-syntax (define-struct->jsexpr stx)
(syntax-parse stx
[(_ id:id s:struct-id)
#:with (own-field ...) (let ([field-prefix (~a (syntax->datum #'s.constructor-id) "-")])
(for/list ([id (syntax-e #'(s.own-accessor-id ...))])
(define id:str (symbol->string (syntax->datum id)))
(datum->syntax id (string->symbol (substring id:str (string-length field-prefix))))))
#'(define (id v)
(make-immutable-hasheq (list (cons 'own-field (s.own-accessor-id v)) ...)))]))
(define-struct->jsexpr person->jsexpr person)
(person->jsexpr (person "Bogdan" 28))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment