lecture16 - 4/7/2009 Topics COMPUTER SCIENCE 51 Spring 2009

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
4/7/2009 1 COMPUTER SCIENCE 51 Spring 2009 cs51.seas.harvard.edu Greg Morrisett & Ramin Zabih Topics • Last Time: – objects, classes, inheritance • This Time: – macros •see PLT Guide – lazy lists or streams •see SICP Macros • Used to extend a language. – see G.Steele’s “Growing a Language” – avoid making the language bigger – provide convenient notation • Many languages have support – C/C++ via the C-pre-processor • works at level of concrete syntax • very error prone; abused frequently – Scheme • works at level of abstract syntax • understands the structure of the language An Example Suppose “or” wasn’t pre-defined. We could try to write: ( define (or x y) (if x true y)) But this isn’t ideal. (or (empty? x) (= 0 (car x))) We want or to be lazy evaluating its second argument, but the default is to evaluate all arguments. Macros to the Rescue So we can instead define a macro: ( define-syntax-rule (or x y) ( if x true y)) This looks just like a function, but: – it operates over syntax, not values – the compiler expands the macro each time it is called. – So writing (or e1 e2) expands into ( if e1 true e2). Another Example Why doesn’t this work? ( define (inc! x) ( set ! x (+ 1 x))) ( define z 0) (inc! z) z ==> 0!!!
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
4/7/2009 2 With a Macro ( define-syntax-rule (inc! x) (set! x (+ 1 x))) ( define z 0) (inc! z) ; same as (set! z (+1 z)) z ==> 1 One More Example ( define-syntax-rule (while t b) ( letrec ([loop ( lambda () ( if t ( begin b (loop)) (void)))]) (loop))) ( let ([x 0] [y 0]) (while (<= x 10) ( begin ( set ! y (+ y x)) (inc! x)))) A Subtlety ( define-syntax-rule (swap x y) ( let ([temp x]) ( begin ( set ! x y) ( set ! y temp)))) ( define temp 42) ( define z 3) (swap temp z)??? Bad Expansion ( define-syntax-rule (swap x y) ( let ([temp x]) ( begin ( set ! x y) ( set ! y temp)))) (swap temp z) expands to ( let ([temp temp]) ( begin ( set ! temp z) ( set ! z temp)))???
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 8

lecture16 - 4/7/2009 Topics COMPUTER SCIENCE 51 Spring 2009

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online