[gambit-list] Newbie: define-macro question

Logan, Patrick D patrick.d.logan at intel.com
Thu Aug 18 14:10:51 EDT 2005


> In your opinion, is it appropriate to use a macro to abstract away
> repetitive boiler-plate code? Or is this better done in a procedure?

This is almost always a procedural abstraction rather than syntax,
especially for beginners with Lisp... better to spend a lot of time
with just procedural abstraction, higher-order functions, etc.

Syntactical abstraction I use for controlling the order of evaluation
and sometimes to put a pretty syntax around use of lambda.

The begin1 is an example of control.

An example of the latter use of pretty syntax... consider a scenario
where you are using a resource and you want some "before" and "after"
actions. The base level way to implement this is with higher-order
procedures. But who wants to write (lambda () ...) all the time? So on
top of this build some pretty syntax. For example...

(define (call-when-ready procedure)
  (wait-until-ready time-out)
  (if (not (ready?))
      (call-when-ready procedure)))

Use it like this...

(call-when-ready 
  (lambda () 
    (display "I am glad this is finally ready!")
    (newline)
    (do-something)))

This is fine when someone else is generating the code for
you. Normally you might want to abstract the procedure as a sequence
of statements...

(when-ready
  (display "I am glad this is finally ready!")
  (newline)
  (do-something))

And so when-ready is defined as a macro that calls call-when-ready...

(define-macro (when-ready . body)
  `(call-when-ready
     (lambda ()
       , at body)))

-Patrick




More information about the Gambit-list mailing list