Arbitrary computation in Scheme macro

2019-04-13 00:16发布

问题:

Scheme macros, at least the syntax-case variety, are said to allow arbitrary computation on the code to be transformed. However (both in the general case and in the specific case I'm currently looking at) this requires the computation to be specified in terms of recursive functions. When I try various variants of this, I get e.g.

main.scm:32:71: compile: unbound identifier in module (in the transformer environment, which does not include the run-time definition) in: expand-vars

(The implementation is Racket, if it matters.)

The upshot seems to be that you can't define named functions until after macro processing.

I suppose I could resort to the Y combinator, but I figure it's worth asking first whether there's a better approach?

回答1:

Yes, the fact that you're using Racket matters -- in Racket, there is something that is called "phase separation", which means that the syntax level cannot use runtime functions. For example, this:

#lang racket
(define (bleh) #'123)
(define-syntax (foo stx)
  (bleh))
(foo)

will not work since bleh is bound at a runtime, not available for syntax. Instead, it should be

(define-for-syntax (bleh) #'123)

or

(begin-for-syntax (define (bleh) #'123))

or moved as an internal definition to the macro body, or moved to its own module and required using (require (for-syntax "bleh.rkt")).