在使用宏构建的 class 定义中动态绑定变量

Dynamically bind a variable inside a class definition built with macro's

情况是这样的:我有一个 class 定义,其 public 方法是使用宏定义的。这些方法看起来像这样:

<-- macro definition surrounds this method -->
(define/public (message-identifier parameters state-values)
    message-body ...) ...

其中所有变量(message-identifierparametersstate-values)都是宏展开的一部分。 message-body 是一个表达式序列,就像您在常规方法体中所期望的那样(由宏扩展生成)。方法的主体可能包含一些也会扩展的形式,例如,如果您想明确声明 return 值,表达式 (return 1) 可能是主体的一部分,我们可以对其应用 (例如)这条规则:

(define-syntax-rule (return value)
    (displayln "i should return a value!"))

我想知道在 class 方法的定义中,在这种情况下,方法主体中包含了 return 语句。那么我可以动态绑定一个变量吗?这个例子不起作用,但它带来了想法。

(define/public (message-identifier parameters state-values)
    (define return-included? #t)
    message-body ...) ...

(define-syntax-rule (return value)
    (begin (set! return-included? value) ; 'return-included?' is undefined
           (displayln "i should return a value!")))

或者我是否可以在扩展方法主体的宏中使用宏做一些奇特的事情,而不是为 return 语句使用单独的宏?

谢谢

有几种方法可以完成此操作,但一种方法是使用 parameters

您可以在宏定义可以看到的地方为 return 包含定义一个参数:

(define return-included? (make-parameter #f))

然后在你的代码中你可以

(define/public (message-identifier parameters state-values)
  (parameterize ([return-included? #f])
    message-body ...))

(define-syntax-rule (return value)
  (begin (return-included? value)
         (displayln "i should return a value!")))

如果您在 message-identifier 方法的主体中查询 return-included? 的值,它将起作用(由于 parameterize,该值将在主体外重置)。由于 parameterize,return 信息将设置为每个方法的本地信息,不会干扰其他方法。


您或许也可以使用 syntax parameters 来解决这个问题,但这更复杂。除非这里关注性能,否则参数更简单。