[plt-scheme] Keyword arguments using syntax/parse

From: Ryan Culpepper (ryanc at ccs.neu.edu)
Date: Sat Aug 29 20:58:03 EDT 2009

Dave Gurnell wrote:
> Hi all,
> 
> I'm experimenting with syntax/parse as a way of implementing optional 
> keyword arguments with default values.
> 
> I've included some test code below. I'm new to this library so I want to 
> make sure I'm not missing anything. Is this the intended approach for 
> this kind of thing?

Yes, that's right. I intend to streamline this a little more soon, but 
for now that's how to do it.

Here's another way that you might find more pleasant: it separates the 
options out into a "splicing syntax class":

(define-syntax (test stx)

   (define-splicing-syntax-class options
     #:attributes (a b)
     (pattern (~seq (~or (~optional (~seq #:a user-a)
                                    #:name "#:a keyword")
                         (~optional (~seq #:b user-b)
                                    #:name "#:b keyword")) ...)
              #:with a (or (attribute user-a) #''default-a)
              #:with b (or (attribute user-b) #''default-b)))

   (syntax-parse stx
     [(_ opt:options)
      #'(list opt.a opt.b)]))

Ryan


> 
> Many thanks,
> 
> -- Dave
> 
> ; keyword-test.ss =================================
> 
> #lang scheme
> 
> (require (for-syntax syntax/parse))
> 
> ; Example macro -----------------------------------
> 
> ; (_ [#:a expr] [#:b expr])
> ;
> ; Expands to (list a b) where a and b:
> ;   - are either specified using #:a and #:b;
> ;   - or take on default values 'default-a and 'default-b.
> 
> (define-syntax (test stx)
>   (syntax-parse stx
>     [(_ (~or (~optional (~seq #:a user-a) #:name "#:a keyword")
>              (~optional (~seq #:b user-b) #:name "#:b keyword")) ...)
> 
>      (with-syntax ([a (or (attribute user-a) #''default-a)]
>                    [b (or (attribute user-b) #''default-b)])
> 
>        #'(list a b))]))
> 
> ; Test code ---------------------------------------
> 
> (test)             ; => '(default-a default-b)
> (test #:a 1)       ; => '(1 default-b)
> (test #:a 1 #:b 2) ; => '(1 2)
> 
> ; =================================================
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _________________________________________________
>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme



Posted on the users mailing list.