[racket] Accessing lambda arguments in a macro

From: Carl Eastlund (cce at ccs.neu.edu)
Date: Fri Sep 16 16:19:15 EDT 2011

The following program should work.  It uses a "syntax parameter" to
reserve the name bar, then redirects that name to the argument to the
lambda inside each use of foo.  The reference material on syntax
parameters is at:

http://docs.racket-lang.org/reference/stxparam.html

#lang racket

(require racket/stxparam)

(define-syntax-parameter bar
  (make-set!-transformer
    (lambda (stx)
      (raise-syntax-error #false
        "cannot use bar except in an argument to foo"
        stx))))

(define-syntax-rule (foo form ...)
  ((lambda (arg)
     (syntax-parameterize {[bar (make-rename-transformer #'arg)]}
       form ...))
   "ARG"))

(foo "Hello")

(foo bar)

--
Carl Eastlund

On Fri, Sep 16, 2011 at 3:46 PM, Daniel MacDougall
<dmacdougall at gmail.com> wrote:
> Is there any way to define a macro that expands out to a lambda, and then
> access the arguments passed to that lambda from outside the macro in the
> calling context?
> Here's an example of what I mean:
>
> #lang racket
>
> (define-syntax-rule (foo form ...)
>   ((lambda (bar) form ...) "ARG"))
>
> (foo "Hello") ; => returns "Hello"
>
> (foo bar)     ; => expand: unbound identifier in module in: bar
>
>
> I'd like access to the "bar" argument on the last line. Is this possible
> with Racket macros?
> Thanks,
> Daniel



Posted on the users mailing list.