PasteRack.org
Paste # 441
2021-01-18 06:40:26

Fork as a new paste.

Paste viewed 277 times.


Embed:

struct->hasheq

#lang racket/base

(require (for-syntax racket/base
                     racket/struct-info
                     syntax/parse))

(define-syntax (struct->hasheq stx)
  (syntax-parse stx
    [(_ type-id:id instance:expr)
     (with-syntax ([(fld-name ...)
                    (struct-field-info-list (syntax-local-value #'type-id))]
                   [(fld-accessor ...)
                    (list-ref (extract-struct-info (syntax-local-value #'type-id)) 3)])
       #'(hasheq (~@ 'fld-name (fld-accessor instance)) ...))]))


(struct a (hello world))

(define a1 (a "hello" "there!"))

(struct->hasheq a a1)