[plt-scheme] Hygienic Macros

From: Eli Barzilay (eli at barzilay.org)
Date: Thu Feb 12 07:21:21 EST 2009

On Feb 12, Paulo J. Matos wrote:
> Hi all,
> 
> What would be a good simple example of an hygienic macro that would
> not work as expected if the macro were not hygienic?  I would like
> an example that would be simple to understand to programming
> language students that are non-schemers. All the ones I have found
> from papers don't seem 'simple' enough.

I do `orelse', which is actually just `or'.  I begin with:

  (define-macro (orelse E1 E2)
    `(let ([tmp ,E1])
       (if tmp
         tmp
         ,E2)))
  (let ([x 1]) (orelse #f x)) --> 1
  (let ([tmp 1]) (orelse #f tmp)) --> #f

I then switch to

  (define-macro (orelse E1 E2)
    `(let ([%%secret-name%% ,E1])
       (if %%secret-name%%
         %%secret-name%%
         ,E1)))

and say that this doesn't work in some cases of nested macros which
will use the same name (but I don't have a good example for this, so
if anyone has one I'll be happy).

The next step is:

  (define-macro (orelse E1 E2)
    (let ([tmp (gensym)]) ; (and I explain what this does)
      `(let ([,tmp ,E1])
         (if ,tmp
           ,tmp
           ,E2))))
  (let ([x 1]) (orelse #f x)) --> 1
  (let ([tmp 1]) (orelse #f tmp)) --> 1
  (let ([if list]) (orelse 1 2)) --> (1 1 2)

(If you want I can mail you my class notes.)

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!


Posted on the users mailing list.