[racket] Wildcard Macro Names?

From: Danny Yoo (dyoo at hashcollision.org)
Date: Wed Jan 23 16:11:00 EST 2013

On Wed, Jan 23, 2013 at 1:32 PM, Scott Klarenbach <scott at pointyhat.ca> wrote:
> Is it possible to have a macro bound to an identifier with wildcards in it?
>
> So, for example, a macro (@*) that would be used for (@x) and (@y), where
> the symbols x and y are available during expansion.
>
> Or is this something that would have to be done at the reader level?  ie, (@
> ...) is the macro, and the reader turns @x and @y into (@ x) and (@ y)
> respectively.


Besides hooking into the reader, you might also hook into the #%top
macro at the language level.

    http://docs.racket-lang.org/reference/__top.html#(form._((quote._~23~25kernel)._~23~25top))



For example:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#lang racket/base

(module my-lang racket/base
  (provide (except-out (all-from-out racket/base) #%top)
           (rename-out (my-top #%top))
           (struct-out at)
           @)

  (require (for-syntax racket/base
                       racket/syntax
                       syntax/parse))

  (struct at (name) #:transparent)

  (define-syntax (@ stx)
    (syntax-parse stx
      [(_ id)
       (syntax/loc stx
         (at 'id))]))

  (define-syntax (my-top stx)
    (syntax-parse stx
      [(_ . id)
       (cond [(and (symbol? (syntax-e #'id))
                   (regexp-match #px"^@(.+)$" (symbol->string (syntax-e #'id))))
              => (lambda (a-match)
                   (define name (format-id stx "~a" (cadr a-match)
#:source stx))
                   (quasisyntax/loc stx
                     (@ #,name)))]
             [else
              (syntax/loc stx
                (#%top . id))])])))


(module example (submod ".." my-lang)
  (printf "This is the value of @x: ~s" @x))

(require (submod "." example))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Posted on the users mailing list.