Programming Languages Dan Grossman 2013: Optional: Variables, Macros, and Hygiene
Programming Languages Dan Grossman 2013: Optional: Variables, Macros, and Hygiene
Programming Languages Dan Grossman 2013: Optional: Variables, Macros, and Hygiene
o macros for doubling are bad style but instructive e!am"les# (define-syntax dbl (syntax-rules()[(dbl x)(+ x x)])) (define-syntax dbl (syntax-rules()[(dbl x)(* 2 x)]))
(dbl (begin (print "hi") 42)) These are not equivalent to each other$ %onsider#
Dan Grossman, Programming 2
Jan-Mar 2013
More examples
ometimes a macro should re&evaluate an argument it is "assed 'f not( as in dbl( then use a local binding as needed# (define-syntax dbl (syntax-rules () [(dbl x) (let ([y x]) (+ y y))]))
Also good style for macros not to have sur"rising evaluation order Good rule of thumb to "reserve left&to&right (define-syntax take )ad e!am"le *fi! +ith a local binding,# (syntax-rules (from) [(take e from e2) (- e2 e )]))
Jan-Mar 2013 Dan Grossman, Programming 3
Jan-Mar 2013 Dan Grossman, Programming )ut instead 6ac0et 7gets it right(8 +hich is "art4of hygiene
2acro#
(define-syntax dbl (syntax-rules () [(dbl x) (* 2 x)])) (let ([* +]) (dbl 42))
3se#
Jan-Mar 2013
Ho
A hygienic macro system# 1$ ecretly renames local variables in macros +ith fresh names 2$ Loo0s u" variables used in macros +here the macro is defined 4either of these rules are follo+ed by the 7na5ve e!"ansion8 most macro systems use /ithout hygiene( macros are much more brittle *non&modular, ;n rare occasions( hygiene is not +hat you +ant 6ac0et has some+hat com"licated su""ort for that
Jan-Mar 2013