Necto
Necto

Reputation: 2654

Are scheme macroses in the same namespace with variables and functions?

I know, that, unlike Common lisp, Scheme has one common namespace for variables and functions. But does macroses also fall there?

It could be separated by time, in which they exists. But in compilation time, when macroses are all expanses, there surely are some function, like list, or cons, which hence exists both runtime and compile time.

Then could I for example write the following:

(define (add a b) (+ a b))

(let-syntax ((add (lambda (x)
                    (syntax-case x ()
                      ((_ a ...) (syntax + a ...))))))
   (display (add 1 2 3))
   (display (reduce-left add 0 '(1 2 3))))

and get 6 6? Or, vice versa, define the macro, and then define the function? And in such expression: (add 1 2) what happen? Will it be a function call, or macro expansion?

Upvotes: 2

Views: 151

Answers (1)

Mark H Weaver
Mark H Weaver

Reputation: 481

Yes, variables and macros are in the same namespace. (I didn't mention procedures because they are merely values that can stored in variables, like numbers or strings.)

Within the body of your 'let-syntax', 'add' always refers to the macro. Everywhere else in your example, 'add' refers to the procedure.

Note that there are two errors in your code:

  1. The 'syntax' expression is not correct; it should be (syntax (+ a ...)).
  2. In your call to 'reduce-left', it is an error to pass the macro 'add' as an argument to a procedure.

I should mention one complication: if you first define 'add' to be a toplevel procedure, then define some other procedures in terms of 'add', and then later redefine 'add' to be a toplevel macro, the results are not well defined and will vary from one implementation to the next. Similarly if 'add' starts out as a toplevel macro and is later redefined as a procedure.

Upvotes: 2

Related Questions