[racket] structure question

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Wed Dec 8 10:25:47 EST 2010

#lang racket

;; -----------------------------------------------------------------------------
;; library module 

;; syntax def
;; definition = ... | (struct/kw name (field ...) options ...)
;; meaning:           (struct name (field ...) options ...) 
;;                     plus keyword-based constructor: name/kw
;; warning: the introduction of name/kw is non-hygienic 

(define-syntax (struct/kw stx)
  (syntax-case stx ()
    [(_ name (field ...) . stuff)
     (let* ([symbol-to-keyword-parameter
             (lambda (s)
               `(,(string->keyword (symbol->string (syntax-e s))) ,s))]
            [args 
             (map symbol-to-keyword-parameter (syntax->list #'(field ...)))]
            [name/kw 
             (datum->syntax stx
                            (string->symbol 
                             (string-append (symbol->string (syntax-e #'name))
                                            "/kw")))])
       #`(begin
           (struct name (field ...) . stuff)
           (define (#,name/kw #,@(foldl append '[] args))
             (name field ...))))]))

;; -----------------------------------------------------------------------------
;; usage example (could be separate module)
(struct/kw book (author title))

(define book1 (book/kw #:title "The Client" #:author "John Grisham" ))

(string=? (book-author book1) "John Grisham")



Posted on the users mailing list.