Macros and Recursion

Macros and Recursion - CS1102: Macros and Recursion Kathi...

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

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CS1102: Macros and Recursion Kathi Fisler, WPI September 28, 2007 This lecture looks at several more macro examples. It aims to show you when you can use recursion safely with macros and when you can’t. 1 Multi-Argument Or We talked about how to define or as a macro, and why it needed to be defined as a macro instead of as a function. As a reminder, we developed the following macro for or (calling it myor to avoid a name clash within Scheme): ( define-syntax myor ( syntax-rules () [( myor e1 e2 ) ( cond [ e1 true ] [ else e2 ])])) This macro limited or to two arguments. The real or macro in Scheme accepts arbitrary numbers of arguments. Here are some examples: > ( or ( = 3 2 )) false > ( or ( = 3 4 ) ( > 6 9 ) ( < 2 7 )) true Let’s change myor to accept an arbitrary number of arguments. How might we write that? First, we need to change the input pattern to expect an arbitrary number of arguments. Then, if e1 isn’t true, check myor on the rest of the inputs: ( define-syntax myor ( syntax-rules () [( myor e1 ...) ( cond [ e1 true ] [ else ( myor ...)])])) Scheme rejects this with an error saying “syntax: missing ellipses with pattern variable in template in: e1”. The problem is in the else clause: you can’t have ... without the variable that goes with it being nearby. We don’t want to insert e1 into the myor in the else clause, so we need to introduce a second pattern variable: ( define-syntax myor ( syntax-rules () [( myor e1 e2 ...) ( cond [ e1 true ] [ else ( myor e2 ...)])])) Trying this on input ( myor ( = 2 2 ) ( > 3 4 )) yields an error “myor: bad syntax in: (myor)”. What happened? Let’s look at the sequence of expansions that Scheme performs to expand uses of myor according to the pattern: 1 (...
View Full Document

This note was uploaded on 02/06/2008 for the course CS 1102 taught by Professor Fisler during the Fall '07 term at WPI.

Page1 / 4

Macros and Recursion - CS1102: Macros and Recursion Kathi...

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

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