0
votes

This code runs fine:

(require syntax/parse/define (only-in racket [#%app racket:#%app]))
(define-syntax-parser #%app
    [(_ Cond {~datum ?} Form1 ...) 
    #'(when Cond Form1 ...)]
    [(_ Cond {~datum ??} Form1 ... {~datum :} Form2 ...) 
    #'(if Cond (begin Form1 ...) (begin Form2 ...))]
    [(_ Xs ...) 
    #'(racket:#%app Xs ...)]
)

(#t ? (displayln 1))
(#t ?? (displayln 1) : (displayln 2))

However, I wish to change ?? to a single ?. Racket shows error, why doesn't Racket match the second syntax?

:: undefined;
 cannot reference an identifier before its definition

Is Racket confused the if syntax with the right above when syntax? How to fix it to use the same ? for both when and if?

1

1 Answers

0
votes

I found it out how, the when is defined first before the if in define-syntax-parser, and its syntax include ellipsis ... which matches everything following it, including the : in if-else.

Fixed it as below, put syntax for if first:

(require syntax/parse/define (only-in racket [#%app racket:#%app]))
(define-syntax-parser #%app
    [(_ Cond {~datum ?} Form1 ... {~datum :} Form2 ...) 
    #'(if Cond (begin Form1 ...) (begin Form2 ...))]
    [(_ Cond {~datum ?} Form1 ...) 
    #'(when Cond Form1 ...)]
    [(_ Xs ...) 
    #'(racket:#%app Xs ...)]
)

(#t ? (displayln 1))
(#t ? (displayln 1) : (displayln 2))