scheme - Racket switch statement macro -


i'm trying make switch statement macro in racket. i'm having trouble figuring out excatly how it. able use function shown below.

(define x 99)  (switch x     [3 (displayln "x 3")]     [4 (displayln "x 4")]     [5 (displayln "x 5")]     ['default (displayln "none of above")]) 

i've tried using pattern matching syntax-case i'm not sure correct approach. racket experts here give me push in right direction?

i believe in not reinventing wheels, here's macro transforming switch equivalent case, slight change use default instead of 'default. (i apologise soegaard, not knowing how use syntax-parse yet, i'll stick traditional syntax-case instead. ;-))

(define-syntax (switch stx)   (define (transform-clause cl)     (syntax-case cl (default)       ((default expr) #'(else expr))       ((val ... expr) #'((val ...) expr))))    (define (transform-clauses cls)     (syntax-case cls ()       ((cl)        (with-syntax ((case-clause (transform-clause #'cl)))          #'(case-clause)))       ((cl rest ...)        (with-syntax ((case-clause (transform-clause #'cl))                      ((case-rest ...) (transform-clauses #'(rest ...))))          #'(case-clause case-rest ...)))))    (syntax-case stx ()     ((_ x clause ...)      (with-syntax (((case-clause ...) (transform-clauses #'(clause ...))))        #'(case x case-clause ...))))) 

the downside of using switch macro, opposed using case, lose ability distinguish between using default match symbol default, vs catch-all. using case still better. :-)

(case x   ((3) (displayln "x 3"))   ((4) (displayln "x 4"))   ((5) (displayln "x 5"))   (else (displayln "none of above"))) 

Comments