PasteRack.org
Paste # 86207
2015-11-28 13:55:31

Fork as a new paste.

Paste viewed 85 times.


Embed:

How to generate keywords from symbols in a macro?

  1. #lang racket
  2.  
  3. #|
  4. I'm trying to create a macro which takes lists of symbols and generates
  5. a function, like so:
  6.   (my-macro (req req2) (opt opt2))
  7. would expand to...
  8.   (lambda (req req2 #:opt [opt ""] #:opt2 [opt2 ""])
  9.     ...)
  10. Now for the life of me, I can't figure out how to generate the keyword arguments.
  11. Here's what I have to generate the required arguments, and it works great:
  12. |#
  13.  
  14. (define-syntax (argreq stx)
  15.   (syntax-parse stx
  16.     [(_ (req:id ...))
  17.      #'(lambda (req ...)
  18.          (list (cons (quote req) req) ...))]))
  19. ; When called like this, it works great
  20. ((argreq (req req2)) "val1" "val2")
  21.  
  22. ;; I can even expand this macro to allow for optional arguments relatively easily
  23. (define-syntax (argboth stx)
  24.   (syntax-parse stx
  25.     [(_ (req:id ...) (opt:id ...))
  26.      #'(lambda (req ... [opt ""] ...)
  27.          (list (cons (quote req) req) ... (cons (quote opt) opt) ...))]))
  28.  
  29. ;;
  30. ;; But _how_ can I generate keywords for all the optional arguments
  31. ;; I came up with this to generate a single keyword from a symbol, but I can't figure out
  32. ;; how to 1) accept more than one symbol, or 2) apply this to the above macro to interweave
  33. ;; the keywords with their optional arguments
  34. ;;
  35. (define-syntax (testkey stx)
  36.   (syntax-parse stx
  37.     [(_ symb:id)
  38.      (with-syntax ([key (datum->syntax stx
  39.                                        (string->keyword (symbol->string (syntax->datum #'symb))))])
  40.        #'(list (quote key)))]))

=>