[racket] beginner question about macros

From: J. Ian Johnson (ianj at ccs.neu.edu)
Date: Sun Dec 4 11:33:16 EST 2011

foo should be in scope at this macro's definition, otherwise you'll have to unhygienically introduce it.

(define-syntax my-macro-aux
  (syntax-rules ()
    [(_ (exprs ...) v) (let ([v foo]) exprs ...)]
    [(_ (exprs ...) v k e rest ...) (my-macro-aux (exprs ... [k e v]) v rest ...)]
    [(_ any ...) (raise-syntax-error #f "Expected even number of inputs to my-macro")]))
(define-syntax my-macro
  (syntax-rules ()
    [(_ kv ...) (my-macro-aux () x kv ...)]))

As for #2, I have no idea why you would want to do that, seeing as those identifiers would be unbound and thus cause a syntax error. But here's a way anyhow.

(define-syntax my-macro-zip
 (syntax-rules ()
   [(_ () () x (exprs ...)) (let ([x foo]) exprs ...)]
   [(_ (k ks ...) (e es ...) x (exprs ...)) (my-macro-zip (ks ...) (es ...) x ((k e x) exprs ...))]))

(define-syntax (my-macro2 stx)
  (syntax-case stx ()
    [(_ ks es)
     (with-syntax ([freshks (generate-temporaries #'(ks ...))])
       #'(my-macro-zip freshks es x ())]
    [(_ (ks ...) (es ...) k e rest ...) (syntax/loc stx (my-macro2-aux (k ks ...) (e es ...) rest ...))]
    [(_ any ...) (raise-syntax-error #f "Expected even number of inputs to my-macro")]))

(define-syntax my-macro2
  (syntax-rules ()
    [(_ kv ...) (my-macro2-aux () () kv ...)]))


-Ian
----- Original Message -----
From: "Răzvan Rotaru" <razvan.rotaru at gmail.com>
To: users at racket-lang.org
Sent: Sunday, December 4, 2011 10:41:48 AM GMT -05:00 US/Canada Eastern
Subject: [racket] beginner question about macros

Hi,

I currently learning scheme macros, and trying to figure out how to do
two particulars things:

1/
(my-macro a 1 b 2 c 3)

should generate:

(let ((x foo))
    (a 1 x)
    (b 2 x)
    (c 3 x))


The order is important.

2/
I need to transform somehow the symbols:

(my-macro a 1 b 2 c 3)

should generate:

(let ((x foo))
    (new-a 1 x)
    (second-b 2 x)
    (another-c 3 x))

I'd like to ask for some hints about how to achieve these two goals.
I'm currently not able to decide whether to use syntax-rules or
syntax-case.

Thanks,
Razvan
_________________________________________________
  For list-related administrative tasks:
  http://lists.racket-lang.org/listinfo/users



Posted on the users mailing list.