Create an identifier in syntax

33 views
Skip to first unread message

Sean Kemplay

unread,
Jan 23, 2020, 9:59:28 AM1/23/20
to Racket Users
Hello,

I am exploring macros and am trying to define a variable at the top level (with the goal in mind to dynamically define a group of functions from a macro).

with-syntax works fine however I was just wondering if it is possible to directly inject an identifier as syntax within syntax - something like the following which does not work!

(define-syntax x
    (lambda (x)
      #`(define ,#'y "y val")))

(x)
y => y: undefined;
 cannot reference an identifier before its definition

this is just to satisfy my own curiosity :-)

Cheers,
Sean

Ryan Culpepper

unread,
Jan 23, 2020, 11:12:44 AM1/23/20
to Sean Kemplay, Racket Users
On 1/23/20 3:59 PM, Sean Kemplay wrote:
> Hello,
>
> I am exploring macros and am trying to define a variable at the top
> level (with the goal in mind to dynamically define a group of functions
> from a macro).
>
> with-syntax works fine however I was just wondering if it is possible to
> directly inject an identifier as syntax within syntax - something like
> the following which does not work!
>
> (define-syntax x
>     (lambda (x)
>       #`(define ,#'y "y val")))
>
> (x)
> y => y: undefined;
>  cannot reference an identifier before its definition

First, to escape a quasisyntax (#`) template you need to use unsyntax
(#,), not unquote (,).

Second, due to hygiene the y from the macro has an extra scope, so you
can't refer to it by typing y at the top level. But you can do this, for
example:

(define-syntax (x2 stx)
#`(begin (define #,#'y "y val") y))

Or you can write a macro that defines a y with the lexical context of
the macro use:

(define-syntax (x3 stx)
#`(define #,(datum->syntax stx 'y) "y val"))

You could also write this macro with with-syntax instead. The way that
you insert an identifier into a syntax template (quasisyntax/unsyntax vs
with-syntax) is independent of the way you create the identifier.

(Note: using the lexical context of the macro use works here, but it's
not always the right answer. Unhygienic macros are complicated.)

Ryan

Sean Kemplay

unread,
Jan 23, 2020, 11:23:59 AM1/23/20
to Racket Users
Hi Ryan,

Thank you SO much for that explenation! Everything now clicks!!

Sean
Reply all
Reply to author
Forward
0 new messages