Re: macro that writes macros
- From: jordi <jordi.burguet.castell@xxxxxxxxx>
- Date: Sun, 30 Dec 2007 05:13:37 -0800 (PST)
On Dec 30, 3:44 am, Barry Margolin <bar...@xxxxxxxxxxxx> wrote:
In article
<915225bf-8cc6-465b-8df5-f7ebc4cbd...@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
jordi.burguet.cast...@xxxxxxxxx wrote:
Hi,
I'm learning lisp and tried to make this little program to write a web
page:
(defmacro new-tag (name)
(let ((sname (string-downcase (symbol-name name))))
`(defmacro ,name (&rest content)
`(progn
(format t "<~a>~%" ,',sname)
,@content
(format t "</~a>~%" ,',sname)))))
(new-tag html)
(new-tag head)
(new-tag title)
(new-tag body)
(new-tag p)
;; With that, now a web page can be "self-generated":
(html
(head
(title "My web page"))
(body
(p "Hello world")))
And it works. But then I thought about combining all those "(new-
tag ...)" like this:
(defmacro new-tags (&rest tags)
(dolist (tag tags)
`(new-tag ,tag)))
(new-tags html head title body p)
But it doesn't work! I tried without the "`" nor the "," in the "new-
tags" definition and it doesn't work either. I have been fighting with
this simple-looking problem for a long time, reading docs and stuff,
and I can't make it work anyway nor see what is wrong! Anyone has some
advice on what's going on or what I should check?
Remember, what matters for a macro is what it RETURNS -- this is then
executed in place of the macro call. And your NEW-TAGS macro doesn't
return anything. The body of a DOLIST is executed just for its side
effect, it's not accumulated into the result. In DOLIST, you specify
the return value as the third element of the first sub-form, and it
defaults to NIL.
What you want is:
(defmacro new-tags (&rest tags)
`(progn
,(loop for tag in tags
collect `(new-tag ,tag))))
Indeed! Yes, I finally understand it, and by the way I am pretty happy
with being able to write in such a condensed way with lisp... it works
great. So many thanks, Barry, John and Dan!
jordi
.
- References:
- macro that writes macros
- From: jordi . burguet . castell
- Re: macro that writes macros
- From: Barry Margolin
- macro that writes macros
- Prev by Date: Re: Choosing a new language
- Next by Date: Re: macro that writes macros
- Previous by thread: Re: macro that writes macros
- Next by thread: Re: macro that writes macros
- Index(es):
Relevant Pages
|