[plt-scheme] Unhygienic macro not needed?

From: Sam TH (samth at ccs.neu.edu)
Date: Fri Nov 20 09:10:24 EST 2009

On Fri, Nov 20, 2009 at 8:57 AM, Laurent <laurent.orseau at gmail.com> wrote:
> Hi all,
> Still having difficulties with (hygienic) macros...
> I have the following (simplified) code :
> (define (f1 x)
>   (let ([y (foo x)])
>     (bar x y y)
>     (plop y x y)
>     (baz x y)))
> (define (f2 x)
>   (let ([y (foo x)])
>     (baz x y)))
> As I dislike code repetitions, I want to make a macro that could generate
> either f1 or f2 or any function that has a body between the `let' and the
> `(baz'.
> I want the generated code to be as fast as without using macro. This (as I
> understand it) is the case for `define-syntax' et al.
> Since `bar' has some arguments that are defined inside the function, my
> first (probably bad) guess was to use an unhygienic macro with
> `define-macro'. That was simple and worked. However my code was quite slower
> so I suspect the transformation is not syntactic but is rather done on the
> fly with an eval. And I don't want to be beaten to death by hygienic macro
> programmers either.

`defmacro' in PLT Scheme runs at expansion time, just like all other macros.

> So what is the correct way to (generically) compress this code without
> losing run-time, i.e. to have a syntactical transformation?
> Is it possible to define an hygienic macro without loss of genericity?
> Is there a hygienic macro programming style  that I could automatically use?

How about:

#lang scheme

(define-syntax-rule (mymacro f x y . body)
  (define (f x)
     (let ([y (foo x)]) . body)))

(mymacro f x y
    (bar x y y)
    (plop y x y)
    (baz x y))

(mymacro f2 x y (baz x y))
sam th
samth at ccs.neu.edu

Posted on the users mailing list.