Explanation of macros; Haskell macros

mike420 at ziplip.com mike420 at ziplip.com
Mon Oct 6 19:34:12 EDT 2003


I think others dropped the ball while trying to explain macros
to non-Lispers recently. The examples I saw posted were either
too difficult or easily doable without macros (maybe even easier).
This probably convinced many Pythonistas that Lispers are
complexity-seeking wackos, and macros are cruft. This only 
applies to some people and *their* macros. Most important, 
all of the examples failed to relate to "the common man" :  
typical python user or programming newbie. As they say,
"if you can't explain it ..."

I intend to correct this. The following example relates to
a problem familiar to all Python users and demonstrates 
two uses of macros: syntax improvement and efficiency gain
through compile-time code introspection.

Let's say you do not have the "for" keyword, but you have
"dolist" for iterating a list and "dotimes" - a simple 
index loop. You want to create "for" just like in Python, and
you also want "for i in range(10000): print i" to be efficient
and avoid constructing the big list (maybe you do not have
enough memory). In Lisp, you can acomplish this with the
following macro:

(defmacro for(i in list &rest rest)
  (if (eql 'in in)
    (if (and (listp list)
             (eql (length list) 2)
             (eql 'range (first list))
             (integerp (second list)))
      `(dotimes (,i ,(second list)) , at rest)
      `(dolist (,i ,list) , at rest))
    (error "syntax error")))


You can use it like this:

(for k in (range 10000)
  (print k))

or

(for k in '(666 222 333 111)
  (print "foo")
  (print k))

The macro works by looking at *code* (not values) at 
*compile-time*, and if the right argument is (range xxxx), 
it uses the more efficient "dotimes".

Let me know if the above helped you understand the usefulness
of macros or was just as sucky as the earlier stuff.

BTW, I think Alex made some very good points about 
simplicity and uniformity. I hesitate to say that I agree
with the final verdict, but his reasoning is very sound. 
Lispers who tried to mock him (some outside CLP) just showed 
their own idiocy. This isn't winning Lisp any friends...

Someone pointed out that Haskell has macros. Does anyone
know how they relate to Lisp and Scheme macros? Better, worse,
different? If anyone knows them well, can you show how you 
would do "for i in ...."  using Haskell macros?




More information about the Python-list mailing list