[gambit-list] Request: examples of cool uses of macros

Marc Feeley feeley at iro.umontreal.ca
Fri Jan 25 10:30:27 EST 2013

On 2013-01-25, at 9:47 AM, Jason Felice <jason.m.felice at gmail.com> 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.

Here's a favourite of mine, which I teach in class, and which brings me back to my years learning Pascal.  It allows you to write for loops like this:

  (for i := 1 to 10 do (println (* i i)))

The definition is:

(define-macro (for variable _1 expr1 _2 expr2 _3 expr3)
  `(let ((start ,expr1)
         (end ,expr2)
         (body (lambda (,variable) ,expr3)))

     (define loop
       (lambda (i)
         (if (<= i end)
             (begin (body i) (loop (+ i 1))))))

     (loop start)))


More information about the Gambit-list mailing list