Can Racket macros accept keyword arguments?

I would like to create a syntax form in Racket that can take a keyword argument, as some functions can.

Reducing it to a simple example, I tried to write:

(define-syntax sum-of-products (syntax-rules (#:extra) [(sum-of-products ([ab] ...)) (+ (* ab) ...)] [(sum-of-products ([ab] ...) #:extra extra) (+ extra (* ab) ...)])) 

So then the following will work:

 (sum-of-products ([2 2] [3 3])) โ†’ 13 (sum-of-products ([2 2] [3 3]) #:extra 5) โ†’ 18 

Unfortunately, Racket calls this "bad syntax", so it is obvious that the attempt was incorrect.

Can this be done?

+8
macros scheme racket
source share
1 answer

Keywords in syntactic templates are treated in the same way as literals, such as numbers, etc., so you do not need to specify them as keywords. (This is only for identifiers.) So, the following works (note that I fixed the typo that you had in the second example):

 #lang racket (define-syntax sum-of-products (syntax-rules () [(sum-of-products ([ab] ...)) (+ (* ab) ...)] [(sum-of-products ([ab] ...) #:extra extra) (+ extra (* ab) ...)])) (sum-of-products ([2 2] [3 3])) (sum-of-products ([2 2] [3 3]) #:extra 5) 

See also syntax-parse for a utility that facilitates parsing keywords .

+12
source share

All Articles