I'm learning scheme and having a hard time with the define-syntax part. The tutorials online that I have found are not very helpful, so any help you guys can offer would be greatly appreciated. Basically I need to be able to enter (foreach x : 1 do (display x)) and have it output 1, or enter (foreach x : 1 2 3 4 5 6 do (display x)). I have a start but I'm not sure if I am even on the right track or not. What I have is:

(define-syntax foreach
(syntax-rules ()
[(foreach x : y) (display y)]
[(foreach x : y ...) (display y)]
)
)

(define (display x) x)

Recommended Answers

All 2 Replies

Scheme is a dialect of Lisp, so you might want to look for Lisp/CommonLisp tutorials on the web. I haven't used it for many, many years. The last time was probably when I needed to tweak some Emacs macros. The GNU project has a Common Lisp implementation (Gnu Common Lisp) which is widely supported. Here are some links for Lisp books and tutorials online:

http://www.apl.jhu.edu/~hall/lisp.html
http://services.renderx.com/Content/demos/wikibooks-CL.pdf
http://curry.ateneo.net/~jpv/cs171/LispTutorial.pdf
http://cs.gmu.edu/~sean/lisp/LispTutorial.html

There are a couple of problems with your code: First you redefined display to basically do nothing. With that definition of display you'll never get anything printed to the screen, no matter how you define your foreach macro. You should get rid of your definition of display, and just use the built-in display function.

Then you hardcoded (display x) in your expansion. Since I assume, you're supposed to be able to use arbitrary expressions with foreach, that doesn't make much sense.

On a related note the do part of the foreach syntax isn't present in your pattern.

Also he way it is now, a user would be able to pass in arbitrary expressions in place of :. Once you add do to the pattern, the same thing is going to apply for that as well. To avoid this, you should add do and : as keywords.

Once you've got your patterns sorted out, you should think about what you want your code to expand to. As I said, you can't just hardcode (display x) in the expansion, so you should think of a general construct that your foreach loop can expand to, that binds the given identifier and works with arbitrary expression.

PS: Don't bother reading the links that rubberman posted. The define-syntax facility of Scheme has absolutely nothing in common with the macro system of Common Lisp, so those tutorials are just a red herring.

As far as tutorials about define-syntax go, this one looks pretty decent. And it even uses an example that's pretty close to what you're trying to do, so you shouldn't have a hard time adjusting it to your purposes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.