Explanation of macros; Haskell macros
Rolf Wester
wester at ilt.fraunhofer.de
Tue Oct 7 03:33:37 EDT 2003
mike420 at ziplip.com wrote:
> 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")))
>
>
What will a Pythonista think about Lisp macros when he/she tries:
(defun f (n)
(for i in (range n)
(print i)))
(f 10000)
Maybe the macro should better be written:
(defmacro for (i in list &rest rest)
(if (eql 'in in)
(if (and (listp list)
(eql (length list) 2)
(eql 'range (first list))
(or (integerp (second list)) (symbolp (second list))))
`(if (integerp ,(second list))
(dotimes (,i ,(second list)) , at rest)
(error "not an integer"))
`(dolist (,i ,list) , at rest))
(error "syntax error")))
Rolf Wester
More information about the Python-list
mailing list