[plt-scheme] a simple macro redux

From: Danny Yoo (dyoo at hkn.eecs.berkeley.edu)
Date: Tue Nov 21 23:00:50 EST 2006

On Tue, 21 Nov 2006, michael rice wrote:

> Let's forget about "syntax" for a minute. Here is a
> regular non-hygienic macro that works fine in Common
> Lisp but bombs in Scheme:
> How would one write the macro mac in Scheme?

Hi Michael,

You'll want to read the note at the very bottom of the defmacro.ss 

Important: define-macro is still restricted by MzScheme's phase separation 
rules. This means that a macro cannot access run-time bindings because it 
is executed in the syntax expansion phase. Translating code that involves 
define-macro or defmacro from an implementation without this restriction 
usually implies separating macro related functionality into a 
begin-for-syntax or a module (that will be imported with 
require-for-syntax) and properly distinguishing syntactic information from 
run-time information.

So that issue about phase-separation can't be ignored.  Since your MAC 
macro depends on FUN, FUN still needs to be defined to be visible at the 
right syntax expansion phase.

This can be remedied:

(require (lib "defmacro.ss"))

   (define fun
    (lambda (n)
      (cond ((zero? n) '())
            (else (cons n (fun (- n 1))))))))

(define-macro (mac . n) `(+ ,@(fun n)))

Once you have this, you'll get a different error message, but you should 
be able to instantly see how to fix it.

Good luck to you!

Posted on the users mailing list.