Define-match-expander

about definition-match-extension, there are rare materials and code examples to illustrate concepts. It’s hard for me to “decode” what the documentation says:

(define-match-expander id proc-expr) (define-match-expander id proc-expr proc-expr) 

Binds id to a match expander.

The first subexpression of proc-expr is to evaluate the transformer, which produces a pat on the match. Whenever id appears as the beginning of a pattern, this transformer is set during expansion, the syntax object matches the whole schema (including identifier). Pattern - this is replaced by the result of the transformer.

Transformer created by the second The proc-expr subexpression is used when id is used in the context of the expression. Using the second proc-expr, id can be the given value both inside and outside the patterns.

Can someone give some code examples to illustrate the two uses of define-match-expander here?

+6
macros pattern-matching scheme racket
source share
2 answers

The idea of ​​match-expander is that you can expand the match form to handle new templates for your own design templates.

So here is a (somewhat meaningless) example that defines the form of matching "aba" that matches the patterns of one thing, followed by another thing, followed by the first, and then "aba"):

 #lang racket (define-match-expander aba (lambda stx (syntax-case stx () [((_ ab)) #'(list aba)]))) (match '(3 4 3) [(aba xy) (printf "x = ~a, y = ~a" xy)]) 

The second form allows you to add a separate extension that will be used outside the match patterns, for example:

 #lang racket (define-match-expander aba (lambda stx (syntax-case stx () [((_ ab)) #'(list aba)])) (lambda stx #'(error "please don't use aba outside of patterns."))) (match '(3 4 3) [(aba xy) (printf "x = ~a, y = ~a\n" xy)]) (aba xy) 

Caution: add a couple of parsers around the template? Not sure, sorry.

+5
source share

This is a really old question, but I would like to add an example using the “syntax rules” for the same “aba” template:

 (define-match-expander aba (syntax-rules () [(aba ab) (list aba)])) (match '(3 4 3) [(aba xy) (printf "x = ~a, y = ~a" xy)]) 

The left side (aba ab) is the thing going to match , the right side (list aba) is the substitution.

 (match '(3 4 3) [(aba xy) (printf "x = ~a, y = ~a" xy)]) 

replaced by

 (match '(3 4 3) [(list xyx) (printf "x = ~a, y = ~a" xy)]) 

The nice part is that the new helper works for ALL match-whatever functions, such as:

 (match-define (aba xy) (list 1 2 1)) (printf "x = ~a, y = ~a" xy 
+1
source share

All Articles