[racket] structure question
On Wed, 8 Dec 2010 10:25:47 -0500
Matthias Felleisen <matthias-1vnkWVZi4QaVc3sceRu5cw at public.gmane.org>
wrote:
>
> #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")
>
Thanks very much. This looks really good. Would it be possible to define
a default value for certain members of a structure?
Perhaps like this:
(struct/kw book (author title [details (#:default-value "")]))
or this
(struct/kw book (author title [details #:default]) #:default-value "")
--
Manfred