Jason
An example I use in idiomatic C (as taught in the K&R book, and in "Software Tools")
int main(void) { int c; while ((c = getchar()) != EOF) { putchar(c); } return 0; }
and, with macros:
(define (main) (awhile c (read-char) (not (equal? c #!eof)) (write-char c)) (exit 0))
Note that the two pieces of code are pretty much identical (from Paul Graham originally, I believe). Read (awhile) as "anaphoric while". The definition of awhile is (Gambit-C define-macro low level macros):
; anaphoric while ; (define-macro (awhile var expr pred . body) (let ((loop (gensym 'loop))) `(let ,loop () (aif ,var ,expr ,pred (begin ,@body (,loop))))))
awhile, is pitching the "real" work to macro aif, which is:
; anaphoric if ; (define-macro (aif var expr pred then #!optional else) `(let ((,var ,expr)) (if ,pred ,then ,else)))
but (and this is a serious BUT), this is MUCH EASIER in Gambit-C:
(define EOF #!eof) (define getchar read-char) (define putchar write-char)
and now (the \ enters six mode):
\ int main() { int c; while ((c = getchar()) != EOF) { putchar(); } 0; }
but this is only possible with the "six" syntax of Gambit-C. But, of course, six is implemented as macros anyway.
Tasty thought -- C is just macros (and some reader support) to translate to Scheme... But it really isn't "C", it's a much higher order language, that happens to have a great deal of syntax compatibility.
FredW
On Fri, 2013-01-25 at 09:47 -0500, Jason Felice wrote:
Hi!
Does anyone have any examples of macros which drastically improve readability or simplicity of code? Maybe neat hacks?
Not deep hacks that take a long time to understand, but things which can be used to illustrate why macros are powerful and awesome.
Background:
I'm giving a talk tomorrow on Scheme to prisoners in a job training program. The purpose is to expand their brains by exposing them to concepts they haven't seen before (they don't have Internet access).
The talk is about Scheme and "Code is Data". I've laid the foundation, but am getting to the point where I want to have some flashy and interesting uses of macros.
Any help would be appreciated.
Thanks, -Jason _______________________________________________ Gambit-list mailing list Gambit-list@iro.umontreal.ca https://webmail.iro.umontreal.ca/mailman/listinfo/gambit-list