Programming Languages Dan Grossman 2013: Optional: Variables, Macros, and Hygiene

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Programming Languages Dan Grossman 2013

Optional: Variables, Macros, and Hygiene

Another bad macro


Any function that doubles its argument is fine for clients (define (dbl x) (+ x x)) (define (dbl x) (* 2 x)) These are equivalent to each other

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

Local variables in macros


'n %-%..( defining local variables inside macros is un+ise /hen needed done +ith hac0s li0e !!strange!name"4 1ere is +hy +ith a silly e!am"le# 2acro# (define-syntax dbl (syntax-rules () [(dbl x) (let ([y ]) (* 2 x y))])) (let ([y #]) (dbl y))

3se# 4a5ve e!"ansion#

(let ([y #]) (let ([y ]) (* 2 y y)))

Jan-Mar 2013 Dan Grossman, Programming )ut instead 6ac0et 7gets it right(8 +hich is "art4of hygiene

The other side of hygiene


This also loo0s li0e it +ould do the 7+rong8 thing

2acro#

(define-syntax dbl (syntax-rules () [(dbl x) (* 2 x)])) (let ([* +]) (dbl 42))

3se#

4a5ve e!"ansion# (let ([* +]) (* 2 42))

Jan-Mar 2013

)ut again 6ac0et9s hygienic macros get this right:


Dan Grossman, Programming 5

Ho

hygienic macros or!

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

Dan Grossman, Programming

You might also like