简体   繁体   English

宏模式不匹配

[英]Macro pattern not matching

Full source 全文

So I have a macro for making objects, and it is used like: 因此,我有一个用于制作对象的宏,它的用法如下:

(define ob 
  (class (a 10) (b 20)
         (set-a! (lambda (x) (set! a x)))
         (set-b! (lambda (x) (set! b x)))
         (foo (lambda (x)
                (* (+ a b) (- a b))))))

(ob 'a) -> 10
(ob 'b) -> 20
(ob 'set-a! 50)
(ob 'a) -> 50
(ob 'foo) -> 2100

I added another pattern for having public and private members, 我添加了另一种公共和私人成员的模式,

(define ob
  (class private
         (a 10) (b 20)
         public
         (get-a (lambda (x) a))
         (set-a! (lambda (x) (set! a x)))))

and that works, but for some reason, it wont match this pattern: 并且可行,但是由于某种原因,它不会匹配此模式:

(define ob2
  (class private
         (a 10) (b 20) (c '())
         public
         (get-a (lambda (x) a))
         (get-b (lambda (x) b))
         (set-a! (lambda (x) (set! a x)))
         (set-b! (lambda (x) (set! b x)))
         (push-c! (lambda (x)
                    (set! c (cons x c))))
         (pop-c! (lambda (x)
                   (if (not (eq? c '()))
                       (set! c (cdr c))
                       (error "stack empty!"))))))

The error message for trying to use ob2 is in the source 尝试使用ob2的错误消息在源中

As far as I understand, the first example should not work either, and, in fact, I could not get it to work. 据我了解,第一个示例也不应该起作用,实际上,我无法使它起作用。 I don't think you can use two ellipses on the same level. 我认为您不能在同一水平上使用两个椭圆。 Therefore, it would be easier to define something like 因此,定义类似

(define-syntax class
  (syntax-rules (public private)
    ((class (public (?var ?val) ...) (private  (?var1 ?val1) ...))
     (list  (list ?var ?val) ... (list ?var1 ?val1) ...))))

However, if you have to do it all on the same syntactic level, you could do so by applying the macro recursively, along the following lines: 但是,如果必须在相同的语法级别上全部完成操作,则可以通过以下几行递归应用宏来执行此操作:

(define-syntax testclass
  (syntax-rules (public private)
    ((testclass public (var val) . rest)
     (testclass ((var val)) public . rest))
    ((testclass ((var val) ...) public (var1 val1) . rest)
     (testclass ((var val) ... (var1 val1)) public . rest))
    ((testclass lst public private . rest)
     (list (quote lst) (quote rest)))))

In order to make this more robust, you will have to add rules for empty public and private expressions. 为了使其更强大,您将必须为空的公共和私有表达式添加规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM